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
type_of.rs
// Copyright 2012-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. #![allow(non_camel_case_types)] use middle::trans::adt; use middle::trans::common::*; use middle::trans::foreign; use middle::ty; use util::ppaux; use util::ppaux::Repr; use middle::trans::type_::Type; use syntax::abi; use syntax::ast; use syntax::owned_slice::OwnedSlice; pub fn arg_is_indirect(ccx: &CrateContext, arg_ty: ty::t) -> bool { !type_is_immediate(ccx, arg_ty) } pub fn return_uses_outptr(ccx: &CrateContext, ty: ty::t) -> bool { !type_is_immediate(ccx, ty) } pub fn type_of_explicit_arg(ccx: &CrateContext, arg_ty: ty::t) -> Type { let llty = type_of(ccx, arg_ty); if arg_is_indirect(ccx, arg_ty) { llty.ptr_to() } else { llty } } pub fn type_of_rust_fn(cx: &CrateContext, has_env: bool, inputs: &[ty::t], output: ty::t) -> Type { let mut atys: Vec<Type> = Vec::new(); // Arg 0: Output pointer. // (if the output type is non-immediate) let use_out_pointer = return_uses_outptr(cx, output); let lloutputtype = type_of(cx, output); if use_out_pointer { atys.push(lloutputtype.ptr_to()); } // Arg 1: Environment if has_env { atys.push(Type::i8p(cx)); } //... then explicit args. let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty)); atys.extend(input_tys); // Use the output as the actual return value if it's immediate. if use_out_pointer || return_type_is_void(cx, output) { Type::func(atys.as_slice(), &Type::void(cx)) } else { Type::func(atys.as_slice(), &lloutputtype) } } // Given a function type and a count of ty params, construct an llvm type pub fn type_of_fn_from_ty(cx: &CrateContext, fty: ty::t) -> Type { match ty::get(fty).sty { ty::ty_closure(ref f) => { type_of_rust_fn(cx, true, f.sig.inputs.as_slice(), f.sig.output) } ty::ty_bare_fn(ref f) => { if f.abi == abi::Rust || f.abi == abi::RustIntrinsic { type_of_rust_fn(cx, false, f.sig.inputs.as_slice(), f.sig.output) } else { foreign::lltype_for_foreign_fn(cx, fty) } } _ => { cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn") } } } // A "sizing type" is an LLVM type, the size and alignment of which are // guaranteed to be equivalent to what you would get out of `type_of()`. It's // useful because: // // (1) It may be cheaper to compute the sizing type than the full type if all // you're interested in is the size and/or alignment; // // (2) It won't make any recursive calls to determine the structure of the // type behind pointers. This can help prevent infinite loops for // recursive types. For example, enum types rely on this behavior. pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type { match cx.llsizingtypes.borrow().find_copy(&t) { Some(t) => return t, None => () } let llsizingty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t), ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_str(ty::VstoreUniq) | ty::ty_box(..) | ty::ty_uniq(..) | ty::ty_ptr(..) => Type::i8p(cx), ty::ty_rptr(_, mt) => { match ty::get(mt.ty).sty { ty::ty_vec(_, None) => Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false), _ => Type::i8p(cx), } } ty::ty_str(ty::VstoreSlice(..)) => { Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false) } ty::ty_bare_fn(..) => Type::i8p(cx), ty::ty_closure(..) => Type::struct_(cx, [Type::i8p(cx), Type::i8p(cx)], false), ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_str(ty::VstoreFixed(size)) => Type::array(&Type::i8(cx), size as u64), ty::ty_vec(mt, Some(size)) => { Type::array(&sizing_type_of(cx, mt.ty), size as u64) } ty::ty_tup(..) | ty::ty_enum(..) => { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } ty::ty_struct(..) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { let repr = adt::represent_type(cx, t); adt::sizing_type_of(cx, &*repr) } } ty::ty_self(_) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) | ty::ty_vec(_, None) => { cx.sess().bug(format!("fictitious type {:?} in sizing_type_of()", ty::get(t).sty)) } }; cx.llsizingtypes.borrow_mut().insert(t, llsizingty); llsizingty } // NB: If you update this, be sure to update `sizing_type_of()` as well. pub fn type_of(cx: &CrateContext, t: ty::t) -> Type { // Check the cache. match cx.lltypes.borrow().find(&t) { Some(&llty) => return llty, None => () } debug!("type_of {} {:?}", t.repr(cx.tcx()), t); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain // Rust types are defined as the same LLVM types. If we don't do // this then, e.g. `Option<{myfield: bool}>` would be a different // type than `Option<myrec>`. let t_norm = ty::normalize_ty(cx.tcx(), t); if t!= t_norm { let llty = type_of(cx, t_norm); debug!("--> normalized {} {:?} to {} {:?} llty={}", t.repr(cx.tcx()), t, t_norm.repr(cx.tcx()), t_norm, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); return llty; } let mut llty = match ty::get(t).sty { ty::ty_nil | ty::ty_bot => Type::nil(cx), ty::ty_bool => Type::bool(cx), ty::ty_char => Type::char(cx), ty::ty_int(t) => Type::int_from_ty(cx, t), ty::ty_uint(t) => Type::uint_from_ty(cx, t),
Type::vec(cx, &Type::i8(cx)).ptr_to() } ty::ty_enum(did, ref substs) => { // Only create the named struct, but don't fill it in. We // fill it in *after* placing it into the type cache. This // avoids creating more than one copy of the enum when one // of the enum's variants refers to the enum itself. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, an_enum, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name) } ty::ty_box(typ) => { Type::at_box(cx, type_of(cx, typ)).ptr_to() } ty::ty_uniq(typ) => { match ty::get(typ).sty { ty::ty_vec(mt, None) => Type::vec(cx, &type_of(cx, mt.ty)).ptr_to(), _ => type_of(cx, typ).ptr_to(), } } ty::ty_ptr(ref mt) => type_of(cx, mt.ty).ptr_to(), ty::ty_rptr(_, ref mt) => { match ty::get(mt.ty).sty { ty::ty_vec(mt, None) => { let p_ty = type_of(cx, mt.ty).ptr_to(); let u_ty = Type::uint_from_ty(cx, ast::TyU); Type::struct_(cx, [p_ty, u_ty], false) } _ => type_of(cx, mt.ty).ptr_to(), } } ty::ty_str(ty::VstoreSlice(..)) => { // This means we get a nicer name in the output cx.tn.find_type("str_slice").unwrap() } ty::ty_str(ty::VstoreFixed(n)) => { Type::array(&Type::i8(cx), (n + 1u) as u64) } ty::ty_vec(ref mt, Some(n)) => { Type::array(&type_of(cx, mt.ty), n as u64) } ty::ty_bare_fn(_) => { type_of_fn_from_ty(cx, t).ptr_to() } ty::ty_closure(_) => { let fn_ty = type_of_fn_from_ty(cx, t).ptr_to(); Type::struct_(cx, [fn_ty, Type::i8p(cx)], false) } ty::ty_trait(..) => Type::opaque_trait(cx), ty::ty_tup(..) => { let repr = adt::represent_type(cx, t); adt::type_of(cx, &*repr) } ty::ty_struct(did, ref substs) => { if ty::type_is_simd(cx.tcx(), t) { let et = ty::simd_type(cx.tcx(), t); let n = ty::simd_size(cx.tcx(), t); Type::vector(&type_of(cx, et), n as u64) } else { // Only create the named struct, but don't fill it in. We fill it // in *after* placing it into the type cache. This prevents // infinite recursion with recursive struct types. let repr = adt::represent_type(cx, t); let name = llvm_type_name(cx, a_struct, did, substs.tps.as_slice()); adt::incomplete_type_of(cx, &*repr, name) } } ty::ty_vec(_, None) => cx.sess().bug("type_of with unszied ty_vec"), ty::ty_self(..) => cx.sess().unimpl("type_of with ty_self"), ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"), ty::ty_param(..) => cx.sess().bug("type_of with ty_param"), ty::ty_err(..) => cx.sess().bug("type_of with ty_err") }; debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, cx.tn.type_to_str(llty)); cx.lltypes.borrow_mut().insert(t, llty); // If this was an enum or struct, fill in the type now. match ty::get(t).sty { ty::ty_enum(..) | ty::ty_struct(..) if!ty::type_is_simd(cx.tcx(), t) => { let repr = adt::represent_type(cx, t); adt::finish_type_of(cx, &*repr, &mut llty); } _ => () } return llty; } // Want refinements! (Or case classes, I guess pub enum named_ty { a_struct, an_enum } pub fn llvm_type_name(cx: &CrateContext, what: named_ty, did: ast::DefId, tps: &[ty::t]) -> ~str { let name = match what { a_struct => { "struct" } an_enum => { "enum" } }; let tstr = ppaux::parameterized(cx.tcx(), ty::item_path_str(cx.tcx(), did), &ty::NonerasedRegions(OwnedSlice::empty()), tps, did, false); if did.krate == 0 { format!("{}.{}", name, tstr) } else { format!("{}.{}[\\#{}]", name, tstr, did.krate) } } pub fn type_of_dtor(ccx: &CrateContext, self_ty: ty::t) -> Type { let self_ty = type_of(ccx, self_ty).ptr_to(); Type::func([self_ty], &Type::void(ccx)) }
ty::ty_float(t) => Type::float_from_ty(cx, t), ty::ty_str(ty::VstoreUniq) => {
random_line_split
monad.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. // xfail-fast use std::int; trait vec_monad<A> { fn bind<B:Copy>(&self, f: &fn(&A) -> ~[B]) -> ~[B]; } impl<A> vec_monad<A> for ~[A] { fn bind<B:Copy>(&self, f: &fn(&A) -> ~[B]) -> ~[B] { let mut r = ~[]; for self.iter().advance |elt| { r.push_all_move(f(elt)); } r } } trait option_monad<A> { fn bind<B>(&self, f: &fn(&A) -> Option<B>) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn bind<B>(&self, f: &fn(&A) -> Option<B>) -> Option<B> { match *self { Some(ref a) => { f(a) } None => { None } } } } fn transform(x: Option<int>) -> Option<~str> { x.bind(|n| Some(*n + 1) ).bind(|n| Some(int::to_str(*n)) )
assert!((~[~"hi"]) .bind(|x| ~[x.clone(), *x + ~"!"] ) .bind(|x| ~[x.clone(), *x + ~"?"] ) == ~[~"hi", ~"hi?", ~"hi!", ~"hi!?"]); }
} pub fn main() { assert_eq!(transform(Some(10)), Some(~"11")); assert_eq!(transform(None), None);
random_line_split
monad.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. // xfail-fast use std::int; trait vec_monad<A> { fn bind<B:Copy>(&self, f: &fn(&A) -> ~[B]) -> ~[B]; } impl<A> vec_monad<A> for ~[A] { fn bind<B:Copy>(&self, f: &fn(&A) -> ~[B]) -> ~[B] { let mut r = ~[]; for self.iter().advance |elt| { r.push_all_move(f(elt)); } r } } trait option_monad<A> { fn bind<B>(&self, f: &fn(&A) -> Option<B>) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn
<B>(&self, f: &fn(&A) -> Option<B>) -> Option<B> { match *self { Some(ref a) => { f(a) } None => { None } } } } fn transform(x: Option<int>) -> Option<~str> { x.bind(|n| Some(*n + 1) ).bind(|n| Some(int::to_str(*n)) ) } pub fn main() { assert_eq!(transform(Some(10)), Some(~"11")); assert_eq!(transform(None), None); assert!((~[~"hi"]) .bind(|x| ~[x.clone(), *x + ~"!"] ) .bind(|x| ~[x.clone(), *x + ~"?"] ) == ~[~"hi", ~"hi?", ~"hi!", ~"hi!?"]); }
bind
identifier_name
monad.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. // xfail-fast use std::int; trait vec_monad<A> { fn bind<B:Copy>(&self, f: &fn(&A) -> ~[B]) -> ~[B]; } impl<A> vec_monad<A> for ~[A] { fn bind<B:Copy>(&self, f: &fn(&A) -> ~[B]) -> ~[B] { let mut r = ~[]; for self.iter().advance |elt| { r.push_all_move(f(elt)); } r } } trait option_monad<A> { fn bind<B>(&self, f: &fn(&A) -> Option<B>) -> Option<B>; } impl<A> option_monad<A> for Option<A> { fn bind<B>(&self, f: &fn(&A) -> Option<B>) -> Option<B>
} fn transform(x: Option<int>) -> Option<~str> { x.bind(|n| Some(*n + 1) ).bind(|n| Some(int::to_str(*n)) ) } pub fn main() { assert_eq!(transform(Some(10)), Some(~"11")); assert_eq!(transform(None), None); assert!((~[~"hi"]) .bind(|x| ~[x.clone(), *x + ~"!"] ) .bind(|x| ~[x.clone(), *x + ~"?"] ) == ~[~"hi", ~"hi?", ~"hi!", ~"hi!?"]); }
{ match *self { Some(ref a) => { f(a) } None => { None } } }
identifier_body
test.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. use std::cell::RefCell; use std::hashmap::HashSet; use std::local_data; use std::os; use std::run; use std::str; use extra::tempfile::TempDir; use extra::getopts; use extra::test; use rustc::driver::driver; use rustc::driver::session; use syntax::diagnostic; use syntax::parse; use core; use clean; use clean::Clean; use fold::DocFolder; use html::markdown; use passes; use visit_ast::RustdocVisitor; pub fn run(input: &str, matches: &getopts::Matches) -> int { let parsesess = parse::new_parse_sess(None); let input = driver::file_input(Path::new(input)); let libs = matches.opt_strs("L").map(|s| Path::new(s.as_slice())); let libs = @RefCell::new(libs.move_iter().collect()); let sessopts = @session::options { binary: ~"rustdoc", maybe_sysroot: Some(@os::self_exe_path().unwrap().dir_path()), addl_lib_search_paths: libs, outputs: ~[session::OutputDylib], .. (*session::basic_options()).clone() }; let diagnostic_handler = diagnostic::mk_handler(None); let span_diagnostic_handler = diagnostic::mk_span_handler(diagnostic_handler, parsesess.cm); let sess = driver::build_session_(sessopts, parsesess.cm, @diagnostic::DefaultEmitter as @diagnostic::Emitter, span_diagnostic_handler); let cfg = driver::build_configuration(sess); let crate = driver::phase_1_parse_input(sess, cfg.clone(), &input); let (crate, _) = driver::phase_2_configure_and_expand(sess, cfg, crate); let ctx = @core::DocContext { crate: crate, tycx: None, sess: sess, }; local_data::set(super::ctxtkey, ctx); let mut v = RustdocVisitor::new(ctx, None); v.visit(&ctx.crate); let crate = v.clean(); let (crate, _) = passes::unindent_comments(crate); let (crate, _) = passes::collapse_docs(crate); let mut collector = Collector { tests: ~[], names: ~[], cnt: 0, libs: libs, cratename: crate.name.to_owned(), }; collector.fold_crate(crate); let args = matches.opt_strs("test-args"); let mut args = args.iter().flat_map(|s| s.words()).map(|s| s.to_owned()); let mut args = args.to_owned_vec(); args.unshift(~"rustdoctest"); test::test_main(args, collector.tests); 0 } fn runtest(test: &str, cratename: &str, libs: HashSet<Path>) { let test = maketest(test, cratename); let parsesess = parse::new_parse_sess(None); let input = driver::str_input(test); let sessopts = @session::options { binary: ~"rustdoctest", maybe_sysroot: Some(@os::self_exe_path().unwrap().dir_path()), addl_lib_search_paths: @RefCell::new(libs), outputs: ~[session::OutputExecutable], debugging_opts: session::prefer_dynamic, .. (*session::basic_options()).clone() }; let diagnostic_handler = diagnostic::mk_handler(None); let span_diagnostic_handler = diagnostic::mk_span_handler(diagnostic_handler, parsesess.cm); let sess = driver::build_session_(sessopts, parsesess.cm, @diagnostic::DefaultEmitter as @diagnostic::Emitter, span_diagnostic_handler); let outdir = TempDir::new("rustdoctest").expect("rustdoc needs a tempdir"); let out = Some(outdir.path().clone()); let cfg = driver::build_configuration(sess); driver::compile_input(sess, cfg, &input, &out, &None); let exe = outdir.path().join("rust_out"); let out = run::process_output(exe.as_str().unwrap(), []); match out { None => fail!("couldn't run the test"), Some(out) => { if!out.status.success() { fail!("test executable failed:\n{}", str::from_utf8(out.error)); } } } } fn maketest(s: &str, cratename: &str) -> @str
} pub struct Collector { priv tests: ~[test::TestDescAndFn], priv names: ~[~str], priv libs: @RefCell<HashSet<Path>>, priv cnt: uint, priv cratename: ~str, } impl Collector { pub fn add_test(&mut self, test: &str, ignore: bool, should_fail: bool) { let test = test.to_owned(); let name = format!("{}_{}", self.names.connect("::"), self.cnt); self.cnt += 1; let libs = self.libs.borrow(); let libs = (*libs.get()).clone(); let cratename = self.cratename.to_owned(); debug!("Creating test {}: {}", name, test); self.tests.push(test::TestDescAndFn { desc: test::TestDesc { name: test::DynTestName(name), ignore: ignore, should_fail: should_fail, }, testfn: test::DynTestFn(proc() { runtest(test, cratename, libs); }), }); } } impl DocFolder for Collector { fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> { let pushed = match item.name { Some(ref name) if name.len() == 0 => false, Some(ref name) => { self.names.push(name.to_owned()); true } None => false }; match item.doc_value() { Some(doc) => { self.cnt = 0; markdown::find_testable_code(doc, self); } None => {} } let ret = self.fold_item_recur(item); if pushed { self.names.pop(); } return ret; } }
{ let mut prog = ~r" #[deny(warnings)]; #[allow(unused_variable, dead_assignment, unused_mut, attribute_usage, dead_code)]; "; if s.contains("extra") { prog.push_str("extern mod extra;\n"); } if s.contains(cratename) { prog.push_str(format!("extern mod {};\n", cratename)); } if s.contains("fn main") { prog.push_str(s); } else { prog.push_str("fn main() {\n"); prog.push_str(s); prog.push_str("\n}"); } return prog.to_managed();
identifier_body
test.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. use std::cell::RefCell; use std::hashmap::HashSet; use std::local_data; use std::os; use std::run; use std::str; use extra::tempfile::TempDir; use extra::getopts; use extra::test; use rustc::driver::driver; use rustc::driver::session; use syntax::diagnostic; use syntax::parse; use core; use clean; use clean::Clean; use fold::DocFolder; use html::markdown; use passes; use visit_ast::RustdocVisitor; pub fn run(input: &str, matches: &getopts::Matches) -> int { let parsesess = parse::new_parse_sess(None); let input = driver::file_input(Path::new(input)); let libs = matches.opt_strs("L").map(|s| Path::new(s.as_slice())); let libs = @RefCell::new(libs.move_iter().collect()); let sessopts = @session::options { binary: ~"rustdoc", maybe_sysroot: Some(@os::self_exe_path().unwrap().dir_path()), addl_lib_search_paths: libs, outputs: ~[session::OutputDylib], .. (*session::basic_options()).clone() }; let diagnostic_handler = diagnostic::mk_handler(None); let span_diagnostic_handler = diagnostic::mk_span_handler(diagnostic_handler, parsesess.cm); let sess = driver::build_session_(sessopts, parsesess.cm, @diagnostic::DefaultEmitter as @diagnostic::Emitter, span_diagnostic_handler); let cfg = driver::build_configuration(sess); let crate = driver::phase_1_parse_input(sess, cfg.clone(), &input); let (crate, _) = driver::phase_2_configure_and_expand(sess, cfg, crate); let ctx = @core::DocContext { crate: crate, tycx: None, sess: sess, }; local_data::set(super::ctxtkey, ctx); let mut v = RustdocVisitor::new(ctx, None); v.visit(&ctx.crate); let crate = v.clean(); let (crate, _) = passes::unindent_comments(crate); let (crate, _) = passes::collapse_docs(crate); let mut collector = Collector { tests: ~[], names: ~[], cnt: 0, libs: libs, cratename: crate.name.to_owned(), }; collector.fold_crate(crate); let args = matches.opt_strs("test-args"); let mut args = args.iter().flat_map(|s| s.words()).map(|s| s.to_owned()); let mut args = args.to_owned_vec(); args.unshift(~"rustdoctest"); test::test_main(args, collector.tests); 0 } fn runtest(test: &str, cratename: &str, libs: HashSet<Path>) { let test = maketest(test, cratename); let parsesess = parse::new_parse_sess(None); let input = driver::str_input(test); let sessopts = @session::options { binary: ~"rustdoctest", maybe_sysroot: Some(@os::self_exe_path().unwrap().dir_path()), addl_lib_search_paths: @RefCell::new(libs), outputs: ~[session::OutputExecutable], debugging_opts: session::prefer_dynamic, .. (*session::basic_options()).clone() }; let diagnostic_handler = diagnostic::mk_handler(None); let span_diagnostic_handler = diagnostic::mk_span_handler(diagnostic_handler, parsesess.cm); let sess = driver::build_session_(sessopts, parsesess.cm, @diagnostic::DefaultEmitter as @diagnostic::Emitter, span_diagnostic_handler); let outdir = TempDir::new("rustdoctest").expect("rustdoc needs a tempdir"); let out = Some(outdir.path().clone()); let cfg = driver::build_configuration(sess); driver::compile_input(sess, cfg, &input, &out, &None); let exe = outdir.path().join("rust_out"); let out = run::process_output(exe.as_str().unwrap(), []); match out { None => fail!("couldn't run the test"), Some(out) => { if!out.status.success() { fail!("test executable failed:\n{}", str::from_utf8(out.error)); } } } } fn maketest(s: &str, cratename: &str) -> @str { let mut prog = ~r" #[deny(warnings)]; #[allow(unused_variable, dead_assignment, unused_mut, attribute_usage, dead_code)]; "; if s.contains("extra") { prog.push_str("extern mod extra;\n"); } if s.contains(cratename) { prog.push_str(format!("extern mod {};\n", cratename)); } if s.contains("fn main") { prog.push_str(s); } else { prog.push_str("fn main() {\n"); prog.push_str(s); prog.push_str("\n}"); } return prog.to_managed(); } pub struct Collector { priv tests: ~[test::TestDescAndFn], priv names: ~[~str], priv libs: @RefCell<HashSet<Path>>, priv cnt: uint, priv cratename: ~str, } impl Collector { pub fn add_test(&mut self, test: &str, ignore: bool, should_fail: bool) { let test = test.to_owned(); let name = format!("{}_{}", self.names.connect("::"), self.cnt); self.cnt += 1; let libs = self.libs.borrow(); let libs = (*libs.get()).clone(); let cratename = self.cratename.to_owned(); debug!("Creating test {}: {}", name, test); self.tests.push(test::TestDescAndFn { desc: test::TestDesc { name: test::DynTestName(name), ignore: ignore, should_fail: should_fail, }, testfn: test::DynTestFn(proc() { runtest(test, cratename, libs); }), }); } } impl DocFolder for Collector { fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> { let pushed = match item.name { Some(ref name) if name.len() == 0 => false, Some(ref name) => { self.names.push(name.to_owned()); true } None => false }; match item.doc_value() { Some(doc) => { self.cnt = 0; markdown::find_testable_code(doc, self); } None => {} } let ret = self.fold_item_recur(item); if pushed { self.names.pop(); }
}
return ret; }
random_line_split
test.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. use std::cell::RefCell; use std::hashmap::HashSet; use std::local_data; use std::os; use std::run; use std::str; use extra::tempfile::TempDir; use extra::getopts; use extra::test; use rustc::driver::driver; use rustc::driver::session; use syntax::diagnostic; use syntax::parse; use core; use clean; use clean::Clean; use fold::DocFolder; use html::markdown; use passes; use visit_ast::RustdocVisitor; pub fn run(input: &str, matches: &getopts::Matches) -> int { let parsesess = parse::new_parse_sess(None); let input = driver::file_input(Path::new(input)); let libs = matches.opt_strs("L").map(|s| Path::new(s.as_slice())); let libs = @RefCell::new(libs.move_iter().collect()); let sessopts = @session::options { binary: ~"rustdoc", maybe_sysroot: Some(@os::self_exe_path().unwrap().dir_path()), addl_lib_search_paths: libs, outputs: ~[session::OutputDylib], .. (*session::basic_options()).clone() }; let diagnostic_handler = diagnostic::mk_handler(None); let span_diagnostic_handler = diagnostic::mk_span_handler(diagnostic_handler, parsesess.cm); let sess = driver::build_session_(sessopts, parsesess.cm, @diagnostic::DefaultEmitter as @diagnostic::Emitter, span_diagnostic_handler); let cfg = driver::build_configuration(sess); let crate = driver::phase_1_parse_input(sess, cfg.clone(), &input); let (crate, _) = driver::phase_2_configure_and_expand(sess, cfg, crate); let ctx = @core::DocContext { crate: crate, tycx: None, sess: sess, }; local_data::set(super::ctxtkey, ctx); let mut v = RustdocVisitor::new(ctx, None); v.visit(&ctx.crate); let crate = v.clean(); let (crate, _) = passes::unindent_comments(crate); let (crate, _) = passes::collapse_docs(crate); let mut collector = Collector { tests: ~[], names: ~[], cnt: 0, libs: libs, cratename: crate.name.to_owned(), }; collector.fold_crate(crate); let args = matches.opt_strs("test-args"); let mut args = args.iter().flat_map(|s| s.words()).map(|s| s.to_owned()); let mut args = args.to_owned_vec(); args.unshift(~"rustdoctest"); test::test_main(args, collector.tests); 0 } fn
(test: &str, cratename: &str, libs: HashSet<Path>) { let test = maketest(test, cratename); let parsesess = parse::new_parse_sess(None); let input = driver::str_input(test); let sessopts = @session::options { binary: ~"rustdoctest", maybe_sysroot: Some(@os::self_exe_path().unwrap().dir_path()), addl_lib_search_paths: @RefCell::new(libs), outputs: ~[session::OutputExecutable], debugging_opts: session::prefer_dynamic, .. (*session::basic_options()).clone() }; let diagnostic_handler = diagnostic::mk_handler(None); let span_diagnostic_handler = diagnostic::mk_span_handler(diagnostic_handler, parsesess.cm); let sess = driver::build_session_(sessopts, parsesess.cm, @diagnostic::DefaultEmitter as @diagnostic::Emitter, span_diagnostic_handler); let outdir = TempDir::new("rustdoctest").expect("rustdoc needs a tempdir"); let out = Some(outdir.path().clone()); let cfg = driver::build_configuration(sess); driver::compile_input(sess, cfg, &input, &out, &None); let exe = outdir.path().join("rust_out"); let out = run::process_output(exe.as_str().unwrap(), []); match out { None => fail!("couldn't run the test"), Some(out) => { if!out.status.success() { fail!("test executable failed:\n{}", str::from_utf8(out.error)); } } } } fn maketest(s: &str, cratename: &str) -> @str { let mut prog = ~r" #[deny(warnings)]; #[allow(unused_variable, dead_assignment, unused_mut, attribute_usage, dead_code)]; "; if s.contains("extra") { prog.push_str("extern mod extra;\n"); } if s.contains(cratename) { prog.push_str(format!("extern mod {};\n", cratename)); } if s.contains("fn main") { prog.push_str(s); } else { prog.push_str("fn main() {\n"); prog.push_str(s); prog.push_str("\n}"); } return prog.to_managed(); } pub struct Collector { priv tests: ~[test::TestDescAndFn], priv names: ~[~str], priv libs: @RefCell<HashSet<Path>>, priv cnt: uint, priv cratename: ~str, } impl Collector { pub fn add_test(&mut self, test: &str, ignore: bool, should_fail: bool) { let test = test.to_owned(); let name = format!("{}_{}", self.names.connect("::"), self.cnt); self.cnt += 1; let libs = self.libs.borrow(); let libs = (*libs.get()).clone(); let cratename = self.cratename.to_owned(); debug!("Creating test {}: {}", name, test); self.tests.push(test::TestDescAndFn { desc: test::TestDesc { name: test::DynTestName(name), ignore: ignore, should_fail: should_fail, }, testfn: test::DynTestFn(proc() { runtest(test, cratename, libs); }), }); } } impl DocFolder for Collector { fn fold_item(&mut self, item: clean::Item) -> Option<clean::Item> { let pushed = match item.name { Some(ref name) if name.len() == 0 => false, Some(ref name) => { self.names.push(name.to_owned()); true } None => false }; match item.doc_value() { Some(doc) => { self.cnt = 0; markdown::find_testable_code(doc, self); } None => {} } let ret = self.fold_item_recur(item); if pushed { self.names.pop(); } return ret; } }
runtest
identifier_name
lib.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/. */ #![feature(box_syntax)] #![feature(fnbox)] #![feature(mpsc_select)] #![feature(plugin)] #![feature(plugin)] #![plugin(plugins)] #![deny(unsafe_code)] extern crate brotli; extern crate cookie as cookie_rs; extern crate devtools_traits; extern crate flate2; extern crate hyper; extern crate immeta;
#[macro_use] extern crate mime; extern crate mime_guess; extern crate msg; extern crate net_traits; extern crate openssl; extern crate rustc_serialize; extern crate threadpool; extern crate time; #[cfg(any(target_os = "macos", target_os = "linux"))] extern crate tinyfiledialogs; extern crate unicase; extern crate url; extern crate util; extern crate uuid; extern crate webrender_traits; extern crate websocket; pub mod about_loader; pub mod chrome_loader; pub mod cookie; pub mod cookie_storage; pub mod data_loader; pub mod file_loader; pub mod hsts; pub mod http_loader; pub mod image_cache_thread; pub mod mime_classifier; pub mod pub_domains; pub mod resource_thread; pub mod storage_thread; pub mod websocket_loader; /// An implementation of the [Fetch specification](https://fetch.spec.whatwg.org/) pub mod fetch { pub mod cors_cache; pub mod methods; }
extern crate ipc_channel; #[macro_use] extern crate log;
random_line_split
reaction.rs
use chrono::{offset::Utc, DateTime}; use diesel::{self, pg::PgConnection}; use super::Comment; use schema::reactions; use sql_types::ReactionType; #[derive(Debug, Identifiable, Queryable, QueryableByName)] #[table_name = "reactions"] pub struct Reaction { id: i32, reaction_type: ReactionType, comment_id: i32, // foreign key to Comment created_at: DateTime<Utc>, updated_at: DateTime<Utc>, } impl Reaction { pub fn id(&self) -> i32
pub fn reaction_type(&self) -> ReactionType { self.reaction_type } pub fn comment_id(&self) -> i32 { self.comment_id } } #[derive(Insertable)] #[table_name = "reactions"] pub struct NewReaction { reaction_type: ReactionType, comment_id: i32, } impl NewReaction { pub fn insert(self, conn: &PgConnection) -> Result<Reaction, diesel::result::Error> { use diesel::prelude::*; diesel::insert_into(reactions::table) .values(&self) .get_result(conn) } pub fn new(reaction_type: ReactionType, comment: &Comment) -> Self { NewReaction { reaction_type, comment_id: comment.id(), } } } #[cfg(test)] mod tests { use test_helper::*; #[test] fn create_reaction() { with_connection(|conn| { make_post(conn, |conversation_post| { make_post(conn, |comment_post| { with_comment( conn, &conversation_post, &conversation_post, &comment_post, |comment| with_reaction(conn, &comment, |_| Ok(())), ) }) }) }) } }
{ self.id }
identifier_body
reaction.rs
use chrono::{offset::Utc, DateTime}; use diesel::{self, pg::PgConnection}; use super::Comment; use schema::reactions; use sql_types::ReactionType; #[derive(Debug, Identifiable, Queryable, QueryableByName)] #[table_name = "reactions"] pub struct Reaction { id: i32, reaction_type: ReactionType, comment_id: i32, // foreign key to Comment created_at: DateTime<Utc>, updated_at: DateTime<Utc>, } impl Reaction { pub fn id(&self) -> i32 { self.id } pub fn reaction_type(&self) -> ReactionType { self.reaction_type } pub fn comment_id(&self) -> i32 { self.comment_id } } #[derive(Insertable)] #[table_name = "reactions"] pub struct
{ reaction_type: ReactionType, comment_id: i32, } impl NewReaction { pub fn insert(self, conn: &PgConnection) -> Result<Reaction, diesel::result::Error> { use diesel::prelude::*; diesel::insert_into(reactions::table) .values(&self) .get_result(conn) } pub fn new(reaction_type: ReactionType, comment: &Comment) -> Self { NewReaction { reaction_type, comment_id: comment.id(), } } } #[cfg(test)] mod tests { use test_helper::*; #[test] fn create_reaction() { with_connection(|conn| { make_post(conn, |conversation_post| { make_post(conn, |comment_post| { with_comment( conn, &conversation_post, &conversation_post, &comment_post, |comment| with_reaction(conn, &comment, |_| Ok(())), ) }) }) }) } }
NewReaction
identifier_name
reaction.rs
use chrono::{offset::Utc, DateTime}; use diesel::{self, pg::PgConnection}; use super::Comment; use schema::reactions; use sql_types::ReactionType; #[derive(Debug, Identifiable, Queryable, QueryableByName)] #[table_name = "reactions"] pub struct Reaction { id: i32, reaction_type: ReactionType, comment_id: i32, // foreign key to Comment created_at: DateTime<Utc>, updated_at: DateTime<Utc>, } impl Reaction { pub fn id(&self) -> i32 { self.id } pub fn reaction_type(&self) -> ReactionType { self.reaction_type } pub fn comment_id(&self) -> i32 { self.comment_id } } #[derive(Insertable)] #[table_name = "reactions"] pub struct NewReaction { reaction_type: ReactionType, comment_id: i32, } impl NewReaction { pub fn insert(self, conn: &PgConnection) -> Result<Reaction, diesel::result::Error> { use diesel::prelude::*; diesel::insert_into(reactions::table) .values(&self) .get_result(conn) } pub fn new(reaction_type: ReactionType, comment: &Comment) -> Self { NewReaction { reaction_type, comment_id: comment.id(), } } }
use test_helper::*; #[test] fn create_reaction() { with_connection(|conn| { make_post(conn, |conversation_post| { make_post(conn, |comment_post| { with_comment( conn, &conversation_post, &conversation_post, &comment_post, |comment| with_reaction(conn, &comment, |_| Ok(())), ) }) }) }) } }
#[cfg(test)] mod tests {
random_line_split
effects.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 CSS values related to effects. #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; /// A generic value for a single `box-shadow`. #[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] pub struct BoxShadow<Color, SizeLength, BlurShapeLength, ShapeLength> { /// The base shadow. pub base: SimpleShadow<Color, SizeLength, BlurShapeLength>, /// The spread radius. pub spread: ShapeLength, /// Whether this is an inset box shadow. #[animation(constant)] #[css(represents_keyword)] pub inset: bool, } /// A generic value for a single `filter`. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] pub enum Filter<Angle, Factor, Length, DropShadow> { /// `blur(<length>)` #[css(function)] Blur(Length), /// `brightness(<factor>)`
/// `grayscale(<factor>)` #[css(function)] Grayscale(Factor), /// `hue-rotate(<angle>)` #[css(function)] HueRotate(Angle), /// `invert(<factor>)` #[css(function)] Invert(Factor), /// `opacity(<factor>)` #[css(function)] Opacity(Factor), /// `saturate(<factor>)` #[css(function)] Saturate(Factor), /// `sepia(<factor>)` #[css(function)] Sepia(Factor), /// `drop-shadow(...)` #[css(function)] DropShadow(DropShadow), /// `<url>` #[animation(error)] #[cfg(feature = "gecko")] Url(SpecifiedUrl), } /// A generic value for the `drop-shadow()` filter and the `text-shadow` property. /// /// Contrary to the canonical order from the spec, the color is serialised /// first, like in Gecko and Webkit. #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] pub struct SimpleShadow<Color, SizeLength, ShapeLength> { /// Color. pub color: Color, /// Horizontal radius. pub horizontal: SizeLength, /// Vertical radius. pub vertical: SizeLength, /// Blur radius. pub blur: ShapeLength, }
#[css(function)] Brightness(Factor), /// `contrast(<factor>)` #[css(function)] Contrast(Factor),
random_line_split
effects.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 CSS values related to effects. #[cfg(feature = "gecko")] use values::specified::url::SpecifiedUrl; /// A generic value for a single `box-shadow`. #[derive(Animate, Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] pub struct BoxShadow<Color, SizeLength, BlurShapeLength, ShapeLength> { /// The base shadow. pub base: SimpleShadow<Color, SizeLength, BlurShapeLength>, /// The spread radius. pub spread: ShapeLength, /// Whether this is an inset box shadow. #[animation(constant)] #[css(represents_keyword)] pub inset: bool, } /// A generic value for a single `filter`. #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToComputedValue, ToCss)] pub enum Filter<Angle, Factor, Length, DropShadow> { /// `blur(<length>)` #[css(function)] Blur(Length), /// `brightness(<factor>)` #[css(function)] Brightness(Factor), /// `contrast(<factor>)` #[css(function)] Contrast(Factor), /// `grayscale(<factor>)` #[css(function)] Grayscale(Factor), /// `hue-rotate(<angle>)` #[css(function)] HueRotate(Angle), /// `invert(<factor>)` #[css(function)] Invert(Factor), /// `opacity(<factor>)` #[css(function)] Opacity(Factor), /// `saturate(<factor>)` #[css(function)] Saturate(Factor), /// `sepia(<factor>)` #[css(function)] Sepia(Factor), /// `drop-shadow(...)` #[css(function)] DropShadow(DropShadow), /// `<url>` #[animation(error)] #[cfg(feature = "gecko")] Url(SpecifiedUrl), } /// A generic value for the `drop-shadow()` filter and the `text-shadow` property. /// /// Contrary to the canonical order from the spec, the color is serialised /// first, like in Gecko and Webkit. #[derive(Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToAnimatedValue, ToAnimatedZero, ToCss)] pub struct
<Color, SizeLength, ShapeLength> { /// Color. pub color: Color, /// Horizontal radius. pub horizontal: SizeLength, /// Vertical radius. pub vertical: SizeLength, /// Blur radius. pub blur: ShapeLength, }
SimpleShadow
identifier_name
dependency.rs
use semver::VersionReq; use core::{SourceId, Summary, PackageId}; use util::CargoResult; /// Informations about a dependency requested by a Cargo manifest. #[derive(PartialEq,Clone,Debug)] pub struct Dependency { name: String, source_id: SourceId, req: VersionReq, specified_req: Option<String>, kind: Kind, only_match_name: bool, optional: bool, default_features: bool, features: Vec<String>, // This dependency should be used only for this platform. // `None` means *all platforms*. only_for_platform: Option<String>, } #[derive(PartialEq, Clone, Debug, Copy)] pub enum Kind { Normal, Development, Build, } impl Dependency { /// Attempt to create a `Dependency` from an entry in the manifest. pub fn parse(name: &str, version: Option<&str>, source_id: &SourceId) -> CargoResult<Dependency> { let version_req = match version { Some(v) => try!(VersionReq::parse(v)), None => VersionReq::any() }; Ok(Dependency { only_match_name: false, req: version_req, specified_req: version.map(|s| s.to_string()), .. Dependency::new_override(name, source_id) }) } pub fn new_override(name: &str, source_id: &SourceId) -> Dependency { Dependency { name: name.to_string(), source_id: source_id.clone(), req: VersionReq::any(), kind: Kind::Normal, only_match_name: true, optional: false, features: Vec::new(), default_features: true, specified_req: None, only_for_platform: None, } } pub fn version_req(&self) -> &VersionReq { &self.req } pub fn name(&self) -> &str { &self.name } pub fn source_id(&self) -> &SourceId { &self.source_id } pub fn kind(&self) -> Kind { self.kind } pub fn specified_req(&self) -> Option<&str> { self.specified_req.as_ref().map(|s| s.as_slice()) } /// If none, this dependencies must be built for all platforms. /// If some, it must only be built for the specified platform. pub fn only_for_platform(&self) -> Option<&str> { self.only_for_platform.as_ref().map(|s| s.as_slice()) } pub fn
(mut self, kind: Kind) -> Dependency { self.kind = kind; self } /// Sets the list of features requested for the package. pub fn set_features(mut self, features: Vec<String>) -> Dependency { self.features = features; self } /// Sets whether the dependency requests default features of the package. pub fn set_default_features(mut self, default_features: bool) -> Dependency { self.default_features = default_features; self } /// Sets whether the dependency is optional. pub fn set_optional(mut self, optional: bool) -> Dependency { self.optional = optional; self } /// Set the source id for this dependency pub fn set_source_id(mut self, id: SourceId) -> Dependency { self.source_id = id; self } /// Set the version requirement for this dependency pub fn set_version_req(mut self, req: VersionReq) -> Dependency { self.req = req; self } pub fn set_only_for_platform(mut self, platform: Option<String>) -> Dependency { self.only_for_platform = platform; self } /// Lock this dependency to depending on the specified package id pub fn lock_to(self, id: &PackageId) -> Dependency { assert_eq!(self.source_id, *id.source_id()); assert!(self.req.matches(id.version())); self.set_version_req(VersionReq::exact(id.version())) .set_source_id(id.source_id().clone()) } /// Returns false if the dependency is only used to build the local package. pub fn is_transitive(&self) -> bool { match self.kind { Kind::Normal | Kind::Build => true, Kind::Development => false, } } pub fn is_build(&self) -> bool { match self.kind { Kind::Build => true, _ => false } } pub fn is_optional(&self) -> bool { self.optional } /// Returns true if the default features of the dependency are requested. pub fn uses_default_features(&self) -> bool { self.default_features } /// Returns the list of features that are requested by the dependency. pub fn features(&self) -> &[String] { &self.features } /// Returns true if the package (`sum`) can fulfill this dependency request. pub fn matches(&self, sum: &Summary) -> bool { self.matches_id(sum.package_id()) } /// Returns true if the package (`id`) can fulfill this dependency request. pub fn matches_id(&self, id: &PackageId) -> bool { self.name == id.name() && (self.only_match_name || (self.req.matches(id.version()) && &self.source_id == id.source_id())) } /// Returns true if the dependency should be built for this platform. pub fn is_active_for_platform(&self, platform: &str) -> bool { match self.only_for_platform { None => true, Some(ref p) if *p == platform => true, _ => false } } } #[derive(PartialEq,Clone,RustcEncodable)] pub struct SerializedDependency { name: String, req: String } impl SerializedDependency { pub fn from_dependency(dep: &Dependency) -> SerializedDependency { SerializedDependency { name: dep.name().to_string(), req: dep.version_req().to_string() } } }
set_kind
identifier_name
dependency.rs
use semver::VersionReq; use core::{SourceId, Summary, PackageId}; use util::CargoResult; /// Informations about a dependency requested by a Cargo manifest. #[derive(PartialEq,Clone,Debug)] pub struct Dependency { name: String, source_id: SourceId, req: VersionReq, specified_req: Option<String>, kind: Kind, only_match_name: bool, optional: bool, default_features: bool, features: Vec<String>, // This dependency should be used only for this platform. // `None` means *all platforms*. only_for_platform: Option<String>, } #[derive(PartialEq, Clone, Debug, Copy)] pub enum Kind { Normal, Development, Build, } impl Dependency { /// Attempt to create a `Dependency` from an entry in the manifest. pub fn parse(name: &str, version: Option<&str>, source_id: &SourceId) -> CargoResult<Dependency> { let version_req = match version { Some(v) => try!(VersionReq::parse(v)), None => VersionReq::any() }; Ok(Dependency { only_match_name: false, req: version_req, specified_req: version.map(|s| s.to_string()), .. Dependency::new_override(name, source_id) }) } pub fn new_override(name: &str, source_id: &SourceId) -> Dependency { Dependency { name: name.to_string(), source_id: source_id.clone(), req: VersionReq::any(), kind: Kind::Normal, only_match_name: true, optional: false, features: Vec::new(), default_features: true, specified_req: None, only_for_platform: None, } } pub fn version_req(&self) -> &VersionReq { &self.req } pub fn name(&self) -> &str { &self.name } pub fn source_id(&self) -> &SourceId
pub fn kind(&self) -> Kind { self.kind } pub fn specified_req(&self) -> Option<&str> { self.specified_req.as_ref().map(|s| s.as_slice()) } /// If none, this dependencies must be built for all platforms. /// If some, it must only be built for the specified platform. pub fn only_for_platform(&self) -> Option<&str> { self.only_for_platform.as_ref().map(|s| s.as_slice()) } pub fn set_kind(mut self, kind: Kind) -> Dependency { self.kind = kind; self } /// Sets the list of features requested for the package. pub fn set_features(mut self, features: Vec<String>) -> Dependency { self.features = features; self } /// Sets whether the dependency requests default features of the package. pub fn set_default_features(mut self, default_features: bool) -> Dependency { self.default_features = default_features; self } /// Sets whether the dependency is optional. pub fn set_optional(mut self, optional: bool) -> Dependency { self.optional = optional; self } /// Set the source id for this dependency pub fn set_source_id(mut self, id: SourceId) -> Dependency { self.source_id = id; self } /// Set the version requirement for this dependency pub fn set_version_req(mut self, req: VersionReq) -> Dependency { self.req = req; self } pub fn set_only_for_platform(mut self, platform: Option<String>) -> Dependency { self.only_for_platform = platform; self } /// Lock this dependency to depending on the specified package id pub fn lock_to(self, id: &PackageId) -> Dependency { assert_eq!(self.source_id, *id.source_id()); assert!(self.req.matches(id.version())); self.set_version_req(VersionReq::exact(id.version())) .set_source_id(id.source_id().clone()) } /// Returns false if the dependency is only used to build the local package. pub fn is_transitive(&self) -> bool { match self.kind { Kind::Normal | Kind::Build => true, Kind::Development => false, } } pub fn is_build(&self) -> bool { match self.kind { Kind::Build => true, _ => false } } pub fn is_optional(&self) -> bool { self.optional } /// Returns true if the default features of the dependency are requested. pub fn uses_default_features(&self) -> bool { self.default_features } /// Returns the list of features that are requested by the dependency. pub fn features(&self) -> &[String] { &self.features } /// Returns true if the package (`sum`) can fulfill this dependency request. pub fn matches(&self, sum: &Summary) -> bool { self.matches_id(sum.package_id()) } /// Returns true if the package (`id`) can fulfill this dependency request. pub fn matches_id(&self, id: &PackageId) -> bool { self.name == id.name() && (self.only_match_name || (self.req.matches(id.version()) && &self.source_id == id.source_id())) } /// Returns true if the dependency should be built for this platform. pub fn is_active_for_platform(&self, platform: &str) -> bool { match self.only_for_platform { None => true, Some(ref p) if *p == platform => true, _ => false } } } #[derive(PartialEq,Clone,RustcEncodable)] pub struct SerializedDependency { name: String, req: String } impl SerializedDependency { pub fn from_dependency(dep: &Dependency) -> SerializedDependency { SerializedDependency { name: dep.name().to_string(), req: dep.version_req().to_string() } } }
{ &self.source_id }
identifier_body
dependency.rs
use semver::VersionReq; use core::{SourceId, Summary, PackageId}; use util::CargoResult; /// Informations about a dependency requested by a Cargo manifest. #[derive(PartialEq,Clone,Debug)] pub struct Dependency { name: String, source_id: SourceId, req: VersionReq, specified_req: Option<String>, kind: Kind, only_match_name: bool, optional: bool, default_features: bool, features: Vec<String>, // This dependency should be used only for this platform. // `None` means *all platforms*. only_for_platform: Option<String>, } #[derive(PartialEq, Clone, Debug, Copy)] pub enum Kind { Normal, Development, Build, } impl Dependency { /// Attempt to create a `Dependency` from an entry in the manifest. pub fn parse(name: &str, version: Option<&str>, source_id: &SourceId) -> CargoResult<Dependency> { let version_req = match version { Some(v) => try!(VersionReq::parse(v)), None => VersionReq::any() }; Ok(Dependency { only_match_name: false, req: version_req, specified_req: version.map(|s| s.to_string()), .. Dependency::new_override(name, source_id) }) } pub fn new_override(name: &str, source_id: &SourceId) -> Dependency { Dependency { name: name.to_string(), source_id: source_id.clone(), req: VersionReq::any(), kind: Kind::Normal, only_match_name: true, optional: false, features: Vec::new(), default_features: true, specified_req: None, only_for_platform: None, } } pub fn version_req(&self) -> &VersionReq { &self.req } pub fn name(&self) -> &str { &self.name } pub fn source_id(&self) -> &SourceId { &self.source_id } pub fn kind(&self) -> Kind { self.kind } pub fn specified_req(&self) -> Option<&str> { self.specified_req.as_ref().map(|s| s.as_slice()) } /// If none, this dependencies must be built for all platforms. /// If some, it must only be built for the specified platform. pub fn only_for_platform(&self) -> Option<&str> { self.only_for_platform.as_ref().map(|s| s.as_slice()) } pub fn set_kind(mut self, kind: Kind) -> Dependency { self.kind = kind; self } /// Sets the list of features requested for the package. pub fn set_features(mut self, features: Vec<String>) -> Dependency { self.features = features; self } /// Sets whether the dependency requests default features of the package. pub fn set_default_features(mut self, default_features: bool) -> Dependency { self.default_features = default_features; self } /// Sets whether the dependency is optional. pub fn set_optional(mut self, optional: bool) -> Dependency { self.optional = optional; self } /// Set the source id for this dependency pub fn set_source_id(mut self, id: SourceId) -> Dependency { self.source_id = id; self } /// Set the version requirement for this dependency pub fn set_version_req(mut self, req: VersionReq) -> Dependency { self.req = req; self } pub fn set_only_for_platform(mut self, platform: Option<String>) -> Dependency { self.only_for_platform = platform; self } /// Lock this dependency to depending on the specified package id pub fn lock_to(self, id: &PackageId) -> Dependency { assert_eq!(self.source_id, *id.source_id()); assert!(self.req.matches(id.version())); self.set_version_req(VersionReq::exact(id.version())) .set_source_id(id.source_id().clone()) } /// Returns false if the dependency is only used to build the local package. pub fn is_transitive(&self) -> bool { match self.kind { Kind::Normal | Kind::Build => true, Kind::Development => false, } } pub fn is_build(&self) -> bool { match self.kind { Kind::Build => true, _ => false } } pub fn is_optional(&self) -> bool { self.optional } /// Returns true if the default features of the dependency are requested. pub fn uses_default_features(&self) -> bool { self.default_features } /// Returns the list of features that are requested by the dependency. pub fn features(&self) -> &[String] { &self.features } /// Returns true if the package (`sum`) can fulfill this dependency request. pub fn matches(&self, sum: &Summary) -> bool { self.matches_id(sum.package_id()) } /// Returns true if the package (`id`) can fulfill this dependency request. pub fn matches_id(&self, id: &PackageId) -> bool { self.name == id.name() && (self.only_match_name || (self.req.matches(id.version()) && &self.source_id == id.source_id())) } /// Returns true if the dependency should be built for this platform. pub fn is_active_for_platform(&self, platform: &str) -> bool { match self.only_for_platform { None => true, Some(ref p) if *p == platform => true, _ => false } } } #[derive(PartialEq,Clone,RustcEncodable)] pub struct SerializedDependency { name: String,
} impl SerializedDependency { pub fn from_dependency(dep: &Dependency) -> SerializedDependency { SerializedDependency { name: dep.name().to_string(), req: dep.version_req().to_string() } } }
req: String
random_line_split
lib.rs
//! A sample implementation of `multiprocessing.pool.ThreadPool` from Python in //! Rust. //! //! Only a single method is implemented (`imap()`). The implementation of other //! methods is straightforward and is left to the reader. extern crate num_cpus; extern crate threadpool; use std::collections::BTreeMap; use std::sync::Arc; use std::sync::mpsc; /// A thread pool with an interface similar to that of /// `multiprocessing.pool.ThreadPool` from Python. pub struct ThreadPool { /// Internal representation of the thread pool. pool: threadpool::ThreadPool, } impl ThreadPool { /// Creates a new thread pool, where the number of worker threads is /// detected automatically based on the number of available CPUs in the /// system. pub fn new() -> Self { let worker_count = num_cpus::get(); ThreadPool::with_workers(worker_count) } /// Creates a new thread pool with the given number of worker threads. /// /// # Panics /// /// When `count` is negative or zero. pub fn with_workers(count: usize) -> Self { assert!(count > 0, format!("worker count cannot be {}", count)); ThreadPool { pool: threadpool::ThreadPool::new(count), } } /// Returns the number of workers in the pool. pub fn worker_count(&self) -> usize { self.pool.max_count() } /// Applies `f` to all values in `inputs` in parallel and returns an /// iterator over the results. /// /// The order of the returned results matches the order of inputs. That is, /// if you pass it the increment function and `[1, 2, 3]`, you will always /// get the results in this order: `2`, `3`, `4`. pub fn imap<F, I, T, R>(&self, f: F, inputs: I) -> IMapIterator<R> where F: Fn(T) -> R + Send + Sync +'static, I: IntoIterator<Item = T>, T: Send +'static, R: Send +'static, { // We need to wrap the function with Arc so it can be passed to // multiple threads. let f = Arc::new(f); // We use a multiple-producers single-consumer (MPSC) channel to // transfer the results from the thread pool to the user. let (tx, rx) = mpsc::channel(); // Submit `f(input)` for computation in the thread pool, for each // input. We need to keep the total count of submitted computations so // we know when to stop reading results from the channel in // IMapIterator::next(). let mut total = 0; for (i, input) in inputs.into_iter().enumerate() { total += 1; let f = f.clone(); let tx = tx.clone(); self.pool.execute(move || { let result = f(input); if let Err(_) = tx.send((i, result)) { // Sending of the result has failed, which means that the // receiving side has hung up. There is nothing to do but // to ignore the result. } }); } IMapIterator::new(rx, total) } } /// An iterator over results from `ThreadPool::imap()`. pub struct IMapIterator<T> { /// The receiving end of the channel created in `ThreadPool::imap()`. rx: mpsc::Receiver<(usize, T)>, /// As `imap()` preserves the order of the returned results (in contrast to /// `imap_unordered()`), we need a mapping of "indexes" into the original /// input iterator to their corresponding results. results: BTreeMap<usize, T>, /// Index of the next result that we should yield in `next()`. next: usize, /// The total number of results that should be yielded (so we know when to /// stop reading results from the channel. total: usize, } impl<T> IMapIterator<T> { /// Creates a new iterator. fn new(rx: mpsc::Receiver<(usize, T)>, total: usize) -> Self { IMapIterator { rx: rx, results: BTreeMap::new(), next: 0, total: total, } } } impl<T> Iterator for IMapIterator<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { while self.next < self.total { // Do we already have a result for the next index? if let Some(result) = self.results.remove(&self.next) { self.next += 1; return Some(result); } // We do not, so try receiving the next result. let (i, result) = match self.rx.recv() { Ok((i, result)) => (i, result), Err(_) => { // Receiving has failed, which means that the sending side // has hung up. There will be no more results. self.next = self.total; break; }, }; assert!(i >= self.next, format!("got {}, next is {}", i, self.next)); assert!(!self.results.contains_key(&i), format!("{} already exists", i)); self.results.insert(i, result); } None } } #[cfg(test)] mod tests { use super::*; #[test] fn new_sets_number_of_workers_automatically()
#[test] fn with_workers_creates_pool_with_given_number_of_workers() { let pool = ThreadPool::with_workers(4); assert_eq!(pool.worker_count(), 4); } #[test] fn imap_returns_results_in_correct_order() { let pool = ThreadPool::new(); let mut results = Vec::new(); for result in pool.imap(|n| n * 2, &[1, 2, 3, 4, 5]) { results.push(result); } assert_eq!(results, &[2, 4, 6, 8, 10]); } #[test] fn imap_can_be_called_twice_in_row() { let pool = ThreadPool::new(); let mut results = Vec::new(); for result in pool.imap(|n| n * 2, &[1, 2, 3]) { results.push(result); } for result in pool.imap(|n| n * 2, &[4, 5, 6]) { results.push(result); } assert_eq!(results, &[2, 4, 6, 8, 10, 12]); } #[test] fn imap_can_be_called_with_vec() { let pool = ThreadPool::new(); let mut results = Vec::new(); let inputs = vec![1, 2, 3, 4, 5]; for result in pool.imap(|n| n * 2, inputs) { results.push(result); } assert_eq!(results, &[2, 4, 6, 8, 10]); } #[test] fn does_not_panic_when_imap_is_destroyed_before_it_is_consumed() { let pool = ThreadPool::new(); // This immediately drops the returned IMapIterator. pool.imap(|n| n * 2, vec![1_000; 0]); // There is no assertion. We just want to check that we do not panic // when the returned IMapIterator is destroyed before it is consumed. } #[test] fn does_not_panic_when_pool_is_destroyed_before_imap_is_consumed() { let pool = ThreadPool::new(); let results = pool.imap(|n| n * 2, vec![1_000; 0]); ::std::mem::drop(pool); // There is no assertion. We just want to check that we do not panic // when the pool is destroyed before we consume the result from imap(). results.collect::<Vec<_>>(); } }
{ let pool = ThreadPool::new(); assert_eq!(pool.worker_count(), num_cpus::get()); }
identifier_body
lib.rs
//! A sample implementation of `multiprocessing.pool.ThreadPool` from Python in //! Rust. //! //! Only a single method is implemented (`imap()`). The implementation of other //! methods is straightforward and is left to the reader. extern crate num_cpus; extern crate threadpool; use std::collections::BTreeMap; use std::sync::Arc;
/// Internal representation of the thread pool. pool: threadpool::ThreadPool, } impl ThreadPool { /// Creates a new thread pool, where the number of worker threads is /// detected automatically based on the number of available CPUs in the /// system. pub fn new() -> Self { let worker_count = num_cpus::get(); ThreadPool::with_workers(worker_count) } /// Creates a new thread pool with the given number of worker threads. /// /// # Panics /// /// When `count` is negative or zero. pub fn with_workers(count: usize) -> Self { assert!(count > 0, format!("worker count cannot be {}", count)); ThreadPool { pool: threadpool::ThreadPool::new(count), } } /// Returns the number of workers in the pool. pub fn worker_count(&self) -> usize { self.pool.max_count() } /// Applies `f` to all values in `inputs` in parallel and returns an /// iterator over the results. /// /// The order of the returned results matches the order of inputs. That is, /// if you pass it the increment function and `[1, 2, 3]`, you will always /// get the results in this order: `2`, `3`, `4`. pub fn imap<F, I, T, R>(&self, f: F, inputs: I) -> IMapIterator<R> where F: Fn(T) -> R + Send + Sync +'static, I: IntoIterator<Item = T>, T: Send +'static, R: Send +'static, { // We need to wrap the function with Arc so it can be passed to // multiple threads. let f = Arc::new(f); // We use a multiple-producers single-consumer (MPSC) channel to // transfer the results from the thread pool to the user. let (tx, rx) = mpsc::channel(); // Submit `f(input)` for computation in the thread pool, for each // input. We need to keep the total count of submitted computations so // we know when to stop reading results from the channel in // IMapIterator::next(). let mut total = 0; for (i, input) in inputs.into_iter().enumerate() { total += 1; let f = f.clone(); let tx = tx.clone(); self.pool.execute(move || { let result = f(input); if let Err(_) = tx.send((i, result)) { // Sending of the result has failed, which means that the // receiving side has hung up. There is nothing to do but // to ignore the result. } }); } IMapIterator::new(rx, total) } } /// An iterator over results from `ThreadPool::imap()`. pub struct IMapIterator<T> { /// The receiving end of the channel created in `ThreadPool::imap()`. rx: mpsc::Receiver<(usize, T)>, /// As `imap()` preserves the order of the returned results (in contrast to /// `imap_unordered()`), we need a mapping of "indexes" into the original /// input iterator to their corresponding results. results: BTreeMap<usize, T>, /// Index of the next result that we should yield in `next()`. next: usize, /// The total number of results that should be yielded (so we know when to /// stop reading results from the channel. total: usize, } impl<T> IMapIterator<T> { /// Creates a new iterator. fn new(rx: mpsc::Receiver<(usize, T)>, total: usize) -> Self { IMapIterator { rx: rx, results: BTreeMap::new(), next: 0, total: total, } } } impl<T> Iterator for IMapIterator<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { while self.next < self.total { // Do we already have a result for the next index? if let Some(result) = self.results.remove(&self.next) { self.next += 1; return Some(result); } // We do not, so try receiving the next result. let (i, result) = match self.rx.recv() { Ok((i, result)) => (i, result), Err(_) => { // Receiving has failed, which means that the sending side // has hung up. There will be no more results. self.next = self.total; break; }, }; assert!(i >= self.next, format!("got {}, next is {}", i, self.next)); assert!(!self.results.contains_key(&i), format!("{} already exists", i)); self.results.insert(i, result); } None } } #[cfg(test)] mod tests { use super::*; #[test] fn new_sets_number_of_workers_automatically() { let pool = ThreadPool::new(); assert_eq!(pool.worker_count(), num_cpus::get()); } #[test] fn with_workers_creates_pool_with_given_number_of_workers() { let pool = ThreadPool::with_workers(4); assert_eq!(pool.worker_count(), 4); } #[test] fn imap_returns_results_in_correct_order() { let pool = ThreadPool::new(); let mut results = Vec::new(); for result in pool.imap(|n| n * 2, &[1, 2, 3, 4, 5]) { results.push(result); } assert_eq!(results, &[2, 4, 6, 8, 10]); } #[test] fn imap_can_be_called_twice_in_row() { let pool = ThreadPool::new(); let mut results = Vec::new(); for result in pool.imap(|n| n * 2, &[1, 2, 3]) { results.push(result); } for result in pool.imap(|n| n * 2, &[4, 5, 6]) { results.push(result); } assert_eq!(results, &[2, 4, 6, 8, 10, 12]); } #[test] fn imap_can_be_called_with_vec() { let pool = ThreadPool::new(); let mut results = Vec::new(); let inputs = vec![1, 2, 3, 4, 5]; for result in pool.imap(|n| n * 2, inputs) { results.push(result); } assert_eq!(results, &[2, 4, 6, 8, 10]); } #[test] fn does_not_panic_when_imap_is_destroyed_before_it_is_consumed() { let pool = ThreadPool::new(); // This immediately drops the returned IMapIterator. pool.imap(|n| n * 2, vec![1_000; 0]); // There is no assertion. We just want to check that we do not panic // when the returned IMapIterator is destroyed before it is consumed. } #[test] fn does_not_panic_when_pool_is_destroyed_before_imap_is_consumed() { let pool = ThreadPool::new(); let results = pool.imap(|n| n * 2, vec![1_000; 0]); ::std::mem::drop(pool); // There is no assertion. We just want to check that we do not panic // when the pool is destroyed before we consume the result from imap(). results.collect::<Vec<_>>(); } }
use std::sync::mpsc; /// A thread pool with an interface similar to that of /// `multiprocessing.pool.ThreadPool` from Python. pub struct ThreadPool {
random_line_split
lib.rs
//! A sample implementation of `multiprocessing.pool.ThreadPool` from Python in //! Rust. //! //! Only a single method is implemented (`imap()`). The implementation of other //! methods is straightforward and is left to the reader. extern crate num_cpus; extern crate threadpool; use std::collections::BTreeMap; use std::sync::Arc; use std::sync::mpsc; /// A thread pool with an interface similar to that of /// `multiprocessing.pool.ThreadPool` from Python. pub struct ThreadPool { /// Internal representation of the thread pool. pool: threadpool::ThreadPool, } impl ThreadPool { /// Creates a new thread pool, where the number of worker threads is /// detected automatically based on the number of available CPUs in the /// system. pub fn new() -> Self { let worker_count = num_cpus::get(); ThreadPool::with_workers(worker_count) } /// Creates a new thread pool with the given number of worker threads. /// /// # Panics /// /// When `count` is negative or zero. pub fn with_workers(count: usize) -> Self { assert!(count > 0, format!("worker count cannot be {}", count)); ThreadPool { pool: threadpool::ThreadPool::new(count), } } /// Returns the number of workers in the pool. pub fn worker_count(&self) -> usize { self.pool.max_count() } /// Applies `f` to all values in `inputs` in parallel and returns an /// iterator over the results. /// /// The order of the returned results matches the order of inputs. That is, /// if you pass it the increment function and `[1, 2, 3]`, you will always /// get the results in this order: `2`, `3`, `4`. pub fn imap<F, I, T, R>(&self, f: F, inputs: I) -> IMapIterator<R> where F: Fn(T) -> R + Send + Sync +'static, I: IntoIterator<Item = T>, T: Send +'static, R: Send +'static, { // We need to wrap the function with Arc so it can be passed to // multiple threads. let f = Arc::new(f); // We use a multiple-producers single-consumer (MPSC) channel to // transfer the results from the thread pool to the user. let (tx, rx) = mpsc::channel(); // Submit `f(input)` for computation in the thread pool, for each // input. We need to keep the total count of submitted computations so // we know when to stop reading results from the channel in // IMapIterator::next(). let mut total = 0; for (i, input) in inputs.into_iter().enumerate() { total += 1; let f = f.clone(); let tx = tx.clone(); self.pool.execute(move || { let result = f(input); if let Err(_) = tx.send((i, result)) { // Sending of the result has failed, which means that the // receiving side has hung up. There is nothing to do but // to ignore the result. } }); } IMapIterator::new(rx, total) } } /// An iterator over results from `ThreadPool::imap()`. pub struct IMapIterator<T> { /// The receiving end of the channel created in `ThreadPool::imap()`. rx: mpsc::Receiver<(usize, T)>, /// As `imap()` preserves the order of the returned results (in contrast to /// `imap_unordered()`), we need a mapping of "indexes" into the original /// input iterator to their corresponding results. results: BTreeMap<usize, T>, /// Index of the next result that we should yield in `next()`. next: usize, /// The total number of results that should be yielded (so we know when to /// stop reading results from the channel. total: usize, } impl<T> IMapIterator<T> { /// Creates a new iterator. fn new(rx: mpsc::Receiver<(usize, T)>, total: usize) -> Self { IMapIterator { rx: rx, results: BTreeMap::new(), next: 0, total: total, } } } impl<T> Iterator for IMapIterator<T> { type Item = T; fn next(&mut self) -> Option<Self::Item> { while self.next < self.total { // Do we already have a result for the next index? if let Some(result) = self.results.remove(&self.next) { self.next += 1; return Some(result); } // We do not, so try receiving the next result. let (i, result) = match self.rx.recv() { Ok((i, result)) => (i, result), Err(_) => { // Receiving has failed, which means that the sending side // has hung up. There will be no more results. self.next = self.total; break; }, }; assert!(i >= self.next, format!("got {}, next is {}", i, self.next)); assert!(!self.results.contains_key(&i), format!("{} already exists", i)); self.results.insert(i, result); } None } } #[cfg(test)] mod tests { use super::*; #[test] fn new_sets_number_of_workers_automatically() { let pool = ThreadPool::new(); assert_eq!(pool.worker_count(), num_cpus::get()); } #[test] fn with_workers_creates_pool_with_given_number_of_workers() { let pool = ThreadPool::with_workers(4); assert_eq!(pool.worker_count(), 4); } #[test] fn imap_returns_results_in_correct_order() { let pool = ThreadPool::new(); let mut results = Vec::new(); for result in pool.imap(|n| n * 2, &[1, 2, 3, 4, 5]) { results.push(result); } assert_eq!(results, &[2, 4, 6, 8, 10]); } #[test] fn imap_can_be_called_twice_in_row() { let pool = ThreadPool::new(); let mut results = Vec::new(); for result in pool.imap(|n| n * 2, &[1, 2, 3]) { results.push(result); } for result in pool.imap(|n| n * 2, &[4, 5, 6]) { results.push(result); } assert_eq!(results, &[2, 4, 6, 8, 10, 12]); } #[test] fn imap_can_be_called_with_vec() { let pool = ThreadPool::new(); let mut results = Vec::new(); let inputs = vec![1, 2, 3, 4, 5]; for result in pool.imap(|n| n * 2, inputs) { results.push(result); } assert_eq!(results, &[2, 4, 6, 8, 10]); } #[test] fn does_not_panic_when_imap_is_destroyed_before_it_is_consumed() { let pool = ThreadPool::new(); // This immediately drops the returned IMapIterator. pool.imap(|n| n * 2, vec![1_000; 0]); // There is no assertion. We just want to check that we do not panic // when the returned IMapIterator is destroyed before it is consumed. } #[test] fn
() { let pool = ThreadPool::new(); let results = pool.imap(|n| n * 2, vec![1_000; 0]); ::std::mem::drop(pool); // There is no assertion. We just want to check that we do not panic // when the pool is destroyed before we consume the result from imap(). results.collect::<Vec<_>>(); } }
does_not_panic_when_pool_is_destroyed_before_imap_is_consumed
identifier_name
composite_shape_repr.rs
use na; use na::Translate; use math::{Scalar, Point, Vect, Isometry}; use utils::data::hash_map::HashMap; use utils::data::hash::UintTWHash; use entities::bounding_volume::{self, BoundingVolume}; use entities::partitioning::BoundingVolumeInterferencesCollector; use entities::shape::CompositeShape; use entities::inspection::Repr; use entities::inspection; use queries::geometry::Contact; use narrow_phase::{CollisionDetector, CollisionDispatcher, CollisionAlgorithm}; /// Collision detector between a concave shape and another shape. pub struct CompositeShapeRepr<P: Point, M> { prediction: <P::Vect as Vect>::Scalar, sub_detectors: HashMap<usize, CollisionAlgorithm<P, M>, UintTWHash>, to_delete: Vec<usize>, interferences: Vec<usize> } impl<P: Point, M> CompositeShapeRepr<P, M> { /// Creates a new collision detector between a concave shape and another shape. pub fn new(prediction: <P::Vect as Vect>::Scalar) -> CompositeShapeRepr<P, M> { CompositeShapeRepr { prediction: prediction, sub_detectors: HashMap::new_with_capacity(5, UintTWHash::new()), to_delete: Vec::new(), interferences: Vec::new() } } } impl<P, M> CompositeShapeRepr<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn do_update(&mut self, dispatcher: &CollisionDispatcher<P, M>, m1: &M, g1: &CompositeShape<P, M>, m2: &M, g2: &Repr<P, M>, swap: bool) { // Find new collisions let ls_m2 = na::inv(m1).expect("The transformation `m1` must be inversible.") * *m2; let ls_aabb2 = bounding_volume::aabb(g2, &ls_m2).loosened(self.prediction); { let mut visitor = BoundingVolumeInterferencesCollector::new(&ls_aabb2, &mut self.interferences); g1.bvt().visit(&mut visitor); } for i in self.interferences.iter() { let mut detector = None; g1.map_part_at(*i, &mut |_, g1| { let r1 = g1.repr(); let r2 = g2.repr(); if swap { detector = dispatcher.get_collision_algorithm(&r2, &r1) } else { detector = dispatcher.get_collision_algorithm(&r1, &r2) } }); match detector { Some(detector) => { let _ = self.sub_detectors.insert_or_replace(*i, detector, false); }, None => { } } } self.interferences.clear(); // Update all collisions for detector in self.sub_detectors.elements_mut().iter_mut() { let key = detector.key; if ls_aabb2.intersects(g1.aabb_at(key)) { g1.map_transformed_part_at(m1, key, &mut |m1, g1| { if swap { assert!(detector.value.update(dispatcher, m2, g2, m1, g1), "The shape was no longer valid."); } else { assert!(detector.value.update(dispatcher, m1, g1, m2, g2), "The shape was nolonger valid."); } }); } else { // FIXME: ask the detector if it wants to be removed or not self.to_delete.push(key); } } // Remove outdated sub detectors for i in self.to_delete.iter() { self.sub_detectors.remove(i); } self.to_delete.clear(); } } /// Collision detector between a shape and a concave shape. pub struct
<P: Point, M> { sub_detector: CompositeShapeRepr<P, M> } impl<P: Point, M> ReprCompositeShape<P, M> { /// Creates a new collision detector between a shape and a concave shape. pub fn new(prediction: <P::Vect as Vect>::Scalar) -> ReprCompositeShape<P, M> { ReprCompositeShape { sub_detector: CompositeShapeRepr::new(prediction) } } } impl<P, M> CollisionDetector<P, M> for CompositeShapeRepr<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn update(&mut self, d: &CollisionDispatcher<P, M>, ma: &M, a: &Repr<P, M>, mb: &M, b: &Repr<P, M>) -> bool { if let Some(cs) = inspection::maybe_as_composite_shape(a) { self.do_update(d, ma, cs, mb, b, false); true } else { false } } fn num_colls(&self) -> usize { let mut res = 0; for detector in self.sub_detectors.elements().iter() { res = res + detector.value.num_colls() } res } fn colls(&self, out: &mut Vec<Contact<P>>) { for detector in self.sub_detectors.elements().iter() { detector.value.colls(out); } } } impl<P, M> CollisionDetector<P, M> for ReprCompositeShape<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn update(&mut self, d: &CollisionDispatcher<P, M>, ma: &M, a: &Repr<P, M>, mb: &M, b: &Repr<P, M>) -> bool { if let Some(cs) = inspection::maybe_as_composite_shape(b) { self.sub_detector.do_update(d, mb, cs, ma, a, true); true } else { false } } fn num_colls(&self) -> usize { self.sub_detector.num_colls() } fn colls(&self, out: &mut Vec<Contact<P>>) { self.sub_detector.colls(out) } }
ReprCompositeShape
identifier_name
composite_shape_repr.rs
use na; use na::Translate; use math::{Scalar, Point, Vect, Isometry}; use utils::data::hash_map::HashMap; use utils::data::hash::UintTWHash; use entities::bounding_volume::{self, BoundingVolume}; use entities::partitioning::BoundingVolumeInterferencesCollector; use entities::shape::CompositeShape; use entities::inspection::Repr; use entities::inspection; use queries::geometry::Contact; use narrow_phase::{CollisionDetector, CollisionDispatcher, CollisionAlgorithm}; /// Collision detector between a concave shape and another shape. pub struct CompositeShapeRepr<P: Point, M> { prediction: <P::Vect as Vect>::Scalar, sub_detectors: HashMap<usize, CollisionAlgorithm<P, M>, UintTWHash>, to_delete: Vec<usize>, interferences: Vec<usize> } impl<P: Point, M> CompositeShapeRepr<P, M> { /// Creates a new collision detector between a concave shape and another shape. pub fn new(prediction: <P::Vect as Vect>::Scalar) -> CompositeShapeRepr<P, M> { CompositeShapeRepr { prediction: prediction, sub_detectors: HashMap::new_with_capacity(5, UintTWHash::new()), to_delete: Vec::new(), interferences: Vec::new() } } } impl<P, M> CompositeShapeRepr<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn do_update(&mut self, dispatcher: &CollisionDispatcher<P, M>, m1: &M, g1: &CompositeShape<P, M>, m2: &M, g2: &Repr<P, M>, swap: bool) { // Find new collisions let ls_m2 = na::inv(m1).expect("The transformation `m1` must be inversible.") * *m2; let ls_aabb2 = bounding_volume::aabb(g2, &ls_m2).loosened(self.prediction); { let mut visitor = BoundingVolumeInterferencesCollector::new(&ls_aabb2, &mut self.interferences); g1.bvt().visit(&mut visitor); } for i in self.interferences.iter() { let mut detector = None; g1.map_part_at(*i, &mut |_, g1| { let r1 = g1.repr(); let r2 = g2.repr(); if swap { detector = dispatcher.get_collision_algorithm(&r2, &r1) } else { detector = dispatcher.get_collision_algorithm(&r1, &r2) } }); match detector { Some(detector) => { let _ = self.sub_detectors.insert_or_replace(*i, detector, false); }, None => { } } } self.interferences.clear(); // Update all collisions for detector in self.sub_detectors.elements_mut().iter_mut() { let key = detector.key; if ls_aabb2.intersects(g1.aabb_at(key)) { g1.map_transformed_part_at(m1, key, &mut |m1, g1| { if swap { assert!(detector.value.update(dispatcher, m2, g2, m1, g1), "The shape was no longer valid."); } else { assert!(detector.value.update(dispatcher, m1, g1, m2, g2), "The shape was nolonger valid."); } }); } else { // FIXME: ask the detector if it wants to be removed or not self.to_delete.push(key); } } // Remove outdated sub detectors for i in self.to_delete.iter() { self.sub_detectors.remove(i); } self.to_delete.clear(); } } /// Collision detector between a shape and a concave shape. pub struct ReprCompositeShape<P: Point, M> { sub_detector: CompositeShapeRepr<P, M> } impl<P: Point, M> ReprCompositeShape<P, M> { /// Creates a new collision detector between a shape and a concave shape. pub fn new(prediction: <P::Vect as Vect>::Scalar) -> ReprCompositeShape<P, M> { ReprCompositeShape { sub_detector: CompositeShapeRepr::new(prediction) } } } impl<P, M> CollisionDetector<P, M> for CompositeShapeRepr<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn update(&mut self, d: &CollisionDispatcher<P, M>, ma: &M, a: &Repr<P, M>, mb: &M, b: &Repr<P, M>) -> bool { if let Some(cs) = inspection::maybe_as_composite_shape(a) { self.do_update(d, ma, cs, mb, b, false); true } else { false } } fn num_colls(&self) -> usize { let mut res = 0; for detector in self.sub_detectors.elements().iter() { res = res + detector.value.num_colls() } res } fn colls(&self, out: &mut Vec<Contact<P>>) { for detector in self.sub_detectors.elements().iter() { detector.value.colls(out); } } } impl<P, M> CollisionDetector<P, M> for ReprCompositeShape<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn update(&mut self,
d: &CollisionDispatcher<P, M>, ma: &M, a: &Repr<P, M>, mb: &M, b: &Repr<P, M>) -> bool { if let Some(cs) = inspection::maybe_as_composite_shape(b) { self.sub_detector.do_update(d, mb, cs, ma, a, true); true } else { false } } fn num_colls(&self) -> usize { self.sub_detector.num_colls() } fn colls(&self, out: &mut Vec<Contact<P>>) { self.sub_detector.colls(out) } }
random_line_split
composite_shape_repr.rs
use na; use na::Translate; use math::{Scalar, Point, Vect, Isometry}; use utils::data::hash_map::HashMap; use utils::data::hash::UintTWHash; use entities::bounding_volume::{self, BoundingVolume}; use entities::partitioning::BoundingVolumeInterferencesCollector; use entities::shape::CompositeShape; use entities::inspection::Repr; use entities::inspection; use queries::geometry::Contact; use narrow_phase::{CollisionDetector, CollisionDispatcher, CollisionAlgorithm}; /// Collision detector between a concave shape and another shape. pub struct CompositeShapeRepr<P: Point, M> { prediction: <P::Vect as Vect>::Scalar, sub_detectors: HashMap<usize, CollisionAlgorithm<P, M>, UintTWHash>, to_delete: Vec<usize>, interferences: Vec<usize> } impl<P: Point, M> CompositeShapeRepr<P, M> { /// Creates a new collision detector between a concave shape and another shape. pub fn new(prediction: <P::Vect as Vect>::Scalar) -> CompositeShapeRepr<P, M> { CompositeShapeRepr { prediction: prediction, sub_detectors: HashMap::new_with_capacity(5, UintTWHash::new()), to_delete: Vec::new(), interferences: Vec::new() } } } impl<P, M> CompositeShapeRepr<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn do_update(&mut self, dispatcher: &CollisionDispatcher<P, M>, m1: &M, g1: &CompositeShape<P, M>, m2: &M, g2: &Repr<P, M>, swap: bool) { // Find new collisions let ls_m2 = na::inv(m1).expect("The transformation `m1` must be inversible.") * *m2; let ls_aabb2 = bounding_volume::aabb(g2, &ls_m2).loosened(self.prediction); { let mut visitor = BoundingVolumeInterferencesCollector::new(&ls_aabb2, &mut self.interferences); g1.bvt().visit(&mut visitor); } for i in self.interferences.iter() { let mut detector = None; g1.map_part_at(*i, &mut |_, g1| { let r1 = g1.repr(); let r2 = g2.repr(); if swap { detector = dispatcher.get_collision_algorithm(&r2, &r1) } else { detector = dispatcher.get_collision_algorithm(&r1, &r2) } }); match detector { Some(detector) => { let _ = self.sub_detectors.insert_or_replace(*i, detector, false); }, None => { } } } self.interferences.clear(); // Update all collisions for detector in self.sub_detectors.elements_mut().iter_mut() { let key = detector.key; if ls_aabb2.intersects(g1.aabb_at(key)) { g1.map_transformed_part_at(m1, key, &mut |m1, g1| { if swap { assert!(detector.value.update(dispatcher, m2, g2, m1, g1), "The shape was no longer valid."); } else { assert!(detector.value.update(dispatcher, m1, g1, m2, g2), "The shape was nolonger valid."); } }); } else { // FIXME: ask the detector if it wants to be removed or not self.to_delete.push(key); } } // Remove outdated sub detectors for i in self.to_delete.iter() { self.sub_detectors.remove(i); } self.to_delete.clear(); } } /// Collision detector between a shape and a concave shape. pub struct ReprCompositeShape<P: Point, M> { sub_detector: CompositeShapeRepr<P, M> } impl<P: Point, M> ReprCompositeShape<P, M> { /// Creates a new collision detector between a shape and a concave shape. pub fn new(prediction: <P::Vect as Vect>::Scalar) -> ReprCompositeShape<P, M> { ReprCompositeShape { sub_detector: CompositeShapeRepr::new(prediction) } } } impl<P, M> CollisionDetector<P, M> for CompositeShapeRepr<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn update(&mut self, d: &CollisionDispatcher<P, M>, ma: &M, a: &Repr<P, M>, mb: &M, b: &Repr<P, M>) -> bool { if let Some(cs) = inspection::maybe_as_composite_shape(a) { self.do_update(d, ma, cs, mb, b, false); true } else { false } } fn num_colls(&self) -> usize { let mut res = 0; for detector in self.sub_detectors.elements().iter() { res = res + detector.value.num_colls() } res } fn colls(&self, out: &mut Vec<Contact<P>>) { for detector in self.sub_detectors.elements().iter() { detector.value.colls(out); } } } impl<P, M> CollisionDetector<P, M> for ReprCompositeShape<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn update(&mut self, d: &CollisionDispatcher<P, M>, ma: &M, a: &Repr<P, M>, mb: &M, b: &Repr<P, M>) -> bool { if let Some(cs) = inspection::maybe_as_composite_shape(b) { self.sub_detector.do_update(d, mb, cs, ma, a, true); true } else { false } } fn num_colls(&self) -> usize { self.sub_detector.num_colls() } fn colls(&self, out: &mut Vec<Contact<P>>)
}
{ self.sub_detector.colls(out) }
identifier_body
composite_shape_repr.rs
use na; use na::Translate; use math::{Scalar, Point, Vect, Isometry}; use utils::data::hash_map::HashMap; use utils::data::hash::UintTWHash; use entities::bounding_volume::{self, BoundingVolume}; use entities::partitioning::BoundingVolumeInterferencesCollector; use entities::shape::CompositeShape; use entities::inspection::Repr; use entities::inspection; use queries::geometry::Contact; use narrow_phase::{CollisionDetector, CollisionDispatcher, CollisionAlgorithm}; /// Collision detector between a concave shape and another shape. pub struct CompositeShapeRepr<P: Point, M> { prediction: <P::Vect as Vect>::Scalar, sub_detectors: HashMap<usize, CollisionAlgorithm<P, M>, UintTWHash>, to_delete: Vec<usize>, interferences: Vec<usize> } impl<P: Point, M> CompositeShapeRepr<P, M> { /// Creates a new collision detector between a concave shape and another shape. pub fn new(prediction: <P::Vect as Vect>::Scalar) -> CompositeShapeRepr<P, M> { CompositeShapeRepr { prediction: prediction, sub_detectors: HashMap::new_with_capacity(5, UintTWHash::new()), to_delete: Vec::new(), interferences: Vec::new() } } } impl<P, M> CompositeShapeRepr<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn do_update(&mut self, dispatcher: &CollisionDispatcher<P, M>, m1: &M, g1: &CompositeShape<P, M>, m2: &M, g2: &Repr<P, M>, swap: bool) { // Find new collisions let ls_m2 = na::inv(m1).expect("The transformation `m1` must be inversible.") * *m2; let ls_aabb2 = bounding_volume::aabb(g2, &ls_m2).loosened(self.prediction); { let mut visitor = BoundingVolumeInterferencesCollector::new(&ls_aabb2, &mut self.interferences); g1.bvt().visit(&mut visitor); } for i in self.interferences.iter() { let mut detector = None; g1.map_part_at(*i, &mut |_, g1| { let r1 = g1.repr(); let r2 = g2.repr(); if swap { detector = dispatcher.get_collision_algorithm(&r2, &r1) } else { detector = dispatcher.get_collision_algorithm(&r1, &r2) } }); match detector { Some(detector) => { let _ = self.sub_detectors.insert_or_replace(*i, detector, false); }, None => { } } } self.interferences.clear(); // Update all collisions for detector in self.sub_detectors.elements_mut().iter_mut() { let key = detector.key; if ls_aabb2.intersects(g1.aabb_at(key)) { g1.map_transformed_part_at(m1, key, &mut |m1, g1| { if swap { assert!(detector.value.update(dispatcher, m2, g2, m1, g1), "The shape was no longer valid."); } else { assert!(detector.value.update(dispatcher, m1, g1, m2, g2), "The shape was nolonger valid."); } }); } else
} // Remove outdated sub detectors for i in self.to_delete.iter() { self.sub_detectors.remove(i); } self.to_delete.clear(); } } /// Collision detector between a shape and a concave shape. pub struct ReprCompositeShape<P: Point, M> { sub_detector: CompositeShapeRepr<P, M> } impl<P: Point, M> ReprCompositeShape<P, M> { /// Creates a new collision detector between a shape and a concave shape. pub fn new(prediction: <P::Vect as Vect>::Scalar) -> ReprCompositeShape<P, M> { ReprCompositeShape { sub_detector: CompositeShapeRepr::new(prediction) } } } impl<P, M> CollisionDetector<P, M> for CompositeShapeRepr<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn update(&mut self, d: &CollisionDispatcher<P, M>, ma: &M, a: &Repr<P, M>, mb: &M, b: &Repr<P, M>) -> bool { if let Some(cs) = inspection::maybe_as_composite_shape(a) { self.do_update(d, ma, cs, mb, b, false); true } else { false } } fn num_colls(&self) -> usize { let mut res = 0; for detector in self.sub_detectors.elements().iter() { res = res + detector.value.num_colls() } res } fn colls(&self, out: &mut Vec<Contact<P>>) { for detector in self.sub_detectors.elements().iter() { detector.value.colls(out); } } } impl<P, M> CollisionDetector<P, M> for ReprCompositeShape<P, M> where P: Point, P::Vect: Translate<P>, M: Isometry<P, P::Vect> { fn update(&mut self, d: &CollisionDispatcher<P, M>, ma: &M, a: &Repr<P, M>, mb: &M, b: &Repr<P, M>) -> bool { if let Some(cs) = inspection::maybe_as_composite_shape(b) { self.sub_detector.do_update(d, mb, cs, ma, a, true); true } else { false } } fn num_colls(&self) -> usize { self.sub_detector.num_colls() } fn colls(&self, out: &mut Vec<Contact<P>>) { self.sub_detector.colls(out) } }
{ // FIXME: ask the detector if it wants to be removed or not self.to_delete.push(key); }
conditional_block
bytes.rs
use std::net::Ipv4Addr; use byteorder::{ByteOrder, NativeEndian, NetworkEndian}; pub trait BytesAble { fn as_bytes(&self) -> Vec<u8>; #[inline] fn write_bytes(&self, dst: &mut [u8]) { dst.copy_from_slice(&self.as_bytes()); } } pub trait BytesAbleNum { fn as_bytes_be(&self) -> Vec<u8>; fn as_bytes_le(&self) -> Vec<u8>; #[inline] fn write_bytes_be(&self, dst: &mut [u8]) { dst.copy_from_slice(&self.as_bytes_be()); } #[inline] fn write_bytes_le(&self, dst: &mut [u8])
} impl BytesAble for Ipv4Addr { #[inline] fn as_bytes(&self) -> Vec<u8> { self.octets().to_vec() } } impl BytesAble for String { #[inline] fn as_bytes(&self) -> Vec<u8> { self.as_bytes().to_vec() } } macro_rules! impl_bytes_able_for_num_type { ($ty:ty, $size:expr) => { impl BytesAble for $ty { #[inline] fn as_bytes(&self) -> Vec<u8> { self.as_bytes_be().to_vec() } } impl BytesAbleNum for $ty { #[inline] fn as_bytes_be(&self) -> Vec<u8> { let mut bytes = [0u8; $size]; NetworkEndian::write_uint(&mut bytes, u64::from(*self), $size); bytes.to_vec() } #[inline] fn as_bytes_le(&self) -> Vec<u8> { let mut bytes = [0u8; $size]; NativeEndian::write_uint(&mut bytes, u64::from(*self), $size); bytes.to_vec() } } }; } impl_bytes_able_for_num_type!(u64, 8); impl_bytes_able_for_num_type!(u32, 4); impl_bytes_able_for_num_type!(u16, 2);
{ dst.copy_from_slice(&self.as_bytes_le()); }
identifier_body
bytes.rs
use std::net::Ipv4Addr; use byteorder::{ByteOrder, NativeEndian, NetworkEndian}; pub trait BytesAble { fn as_bytes(&self) -> Vec<u8>; #[inline] fn write_bytes(&self, dst: &mut [u8]) { dst.copy_from_slice(&self.as_bytes()); } } pub trait BytesAbleNum { fn as_bytes_be(&self) -> Vec<u8>; fn as_bytes_le(&self) -> Vec<u8>; #[inline] fn write_bytes_be(&self, dst: &mut [u8]) { dst.copy_from_slice(&self.as_bytes_be()); } #[inline] fn write_bytes_le(&self, dst: &mut [u8]) { dst.copy_from_slice(&self.as_bytes_le()); } } impl BytesAble for Ipv4Addr { #[inline] fn as_bytes(&self) -> Vec<u8> { self.octets().to_vec() } } impl BytesAble for String { #[inline] fn as_bytes(&self) -> Vec<u8> { self.as_bytes().to_vec() } } macro_rules! impl_bytes_able_for_num_type { ($ty:ty, $size:expr) => { impl BytesAble for $ty { #[inline] fn as_bytes(&self) -> Vec<u8> { self.as_bytes_be().to_vec() } } impl BytesAbleNum for $ty { #[inline] fn as_bytes_be(&self) -> Vec<u8> { let mut bytes = [0u8; $size]; NetworkEndian::write_uint(&mut bytes, u64::from(*self), $size); bytes.to_vec() } #[inline] fn as_bytes_le(&self) -> Vec<u8> { let mut bytes = [0u8; $size]; NativeEndian::write_uint(&mut bytes, u64::from(*self), $size); bytes.to_vec() } } };
impl_bytes_able_for_num_type!(u64, 8); impl_bytes_able_for_num_type!(u32, 4); impl_bytes_able_for_num_type!(u16, 2);
}
random_line_split
bytes.rs
use std::net::Ipv4Addr; use byteorder::{ByteOrder, NativeEndian, NetworkEndian}; pub trait BytesAble { fn as_bytes(&self) -> Vec<u8>; #[inline] fn
(&self, dst: &mut [u8]) { dst.copy_from_slice(&self.as_bytes()); } } pub trait BytesAbleNum { fn as_bytes_be(&self) -> Vec<u8>; fn as_bytes_le(&self) -> Vec<u8>; #[inline] fn write_bytes_be(&self, dst: &mut [u8]) { dst.copy_from_slice(&self.as_bytes_be()); } #[inline] fn write_bytes_le(&self, dst: &mut [u8]) { dst.copy_from_slice(&self.as_bytes_le()); } } impl BytesAble for Ipv4Addr { #[inline] fn as_bytes(&self) -> Vec<u8> { self.octets().to_vec() } } impl BytesAble for String { #[inline] fn as_bytes(&self) -> Vec<u8> { self.as_bytes().to_vec() } } macro_rules! impl_bytes_able_for_num_type { ($ty:ty, $size:expr) => { impl BytesAble for $ty { #[inline] fn as_bytes(&self) -> Vec<u8> { self.as_bytes_be().to_vec() } } impl BytesAbleNum for $ty { #[inline] fn as_bytes_be(&self) -> Vec<u8> { let mut bytes = [0u8; $size]; NetworkEndian::write_uint(&mut bytes, u64::from(*self), $size); bytes.to_vec() } #[inline] fn as_bytes_le(&self) -> Vec<u8> { let mut bytes = [0u8; $size]; NativeEndian::write_uint(&mut bytes, u64::from(*self), $size); bytes.to_vec() } } }; } impl_bytes_able_for_num_type!(u64, 8); impl_bytes_able_for_num_type!(u32, 4); impl_bytes_able_for_num_type!(u16, 2);
write_bytes
identifier_name
any.rs
// Copyright 2013-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. //! Traits for dynamic typing of any `'static` type (through runtime reflection) //! //! This module implements the `Any` trait, which enables dynamic typing //! of any `'static` type through runtime reflection. //! //! `Any` itself can be used to get a `TypeId`, and has more features when used //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and //! `as_ref` methods, to test if the contained value is of a given type, and to //! get a reference to the inner value as a type. As`&mut Any`, there is also //! the `as_mut` method, for getting a mutable reference to the inner value. //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the //! object. See the extension traits (`*Ext`) for the full details. //! //! Note that &Any is limited to testing whether a value is of a specified //! concrete type, and cannot be used to test whether a type implements a trait. //! //! # Examples //! //! Consider a situation where we want to log out a value passed to a function. //! We know the value we're working on implements Show, but we don't know its //! concrete type. We want to give special treatment to certain types: in this //! case printing out the length of String values prior to their value. //! We don't know the concrete type of our value at compile time, so we need to //! use runtime reflection instead. //! //! ```rust //! use std::fmt::Show; //! use std::any::{Any, AnyRefExt}; //! //! // Logger function for any type that implements Show. //! fn log<T: Any+Show>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to //! // output the String's length as well as its value. If not, it's a //! // different type: just print it out unadorned. //! match value_any.downcast_ref::<String>() { //! Some(as_string) => { //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { //! println!("{}", value); //! } //! } //! } //! //! // This function wants to log its parameter out prior to doing work with it. //! fn do_work<T: Show+'static>(value: &T) { //! log(value); //! //...do some other work //! } //! //! fn main() { //! let my_string = "Hello World".to_string(); //! do_work(&my_string); //! //! let my_i8: i8 = 100; //! do_work(&my_i8); //! } //! ``` #![stable] use mem::{transmute, transmute_copy}; use option::{Option, Some, None}; use raw::TraitObject; use intrinsics::TypeId; /// A type with no inhabitants #[deprecated = "this type is being removed, define a type locally if \ necessary"] pub enum Void { } /////////////////////////////////////////////////////////////////////////////// // Any trait /////////////////////////////////////////////////////////////////////////////// /// The `Any` trait is implemented by all `'static` types, and can be used for /// dynamic typing /// /// Every type with no non-`'static` references implements `Any`, so `Any` can /// be used as a trait object to emulate the effects dynamic typing. #[stable] pub trait Any: AnyPrivate {} /// An inner trait to ensure that only this module can call `get_type_id()`. pub trait AnyPrivate { /// Get the `TypeId` of `self` fn get_type_id(&self) -> TypeId; } impl<T:'static> AnyPrivate for T { fn get_type_id(&self) -> TypeId { TypeId::of::<T>() } } impl<T:'static + AnyPrivate> Any for T {} /////////////////////////////////////////////////////////////////////////////// // Extension methods for Any trait objects. // Implemented as three extension traits so that the methods can be generic. /////////////////////////////////////////////////////////////////////////////// /// Extension methods for a referenced `Any` trait object #[unstable = "this trait will not be necessary once DST lands, it will be a \ part of `impl Any`"] pub trait AnyRefExt<'a> { /// Returns true if the boxed type is the same as `T` #[stable] fn is<T:'static>(self) -> bool; /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] fn downcast_ref<T:'static>(self) -> Option<&'a T>; /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[deprecated = "this function has been renamed to `downcast_ref`"] fn as_ref<T:'static>(self) -> Option<&'a T> { self.downcast_ref::<T>() } } #[stable] impl<'a> AnyRefExt<'a> for &'a Any+'a { #[inline] #[stable] fn is<T:'static>(self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } #[inline] #[unstable = "naming conventions around acquiring references may change"] fn downcast_ref<T:'static>(self) -> Option<&'a T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } } /// Extension methods for a mutable referenced `Any` trait object #[unstable = "this trait will not be necessary once DST lands, it will be a \ part of `impl Any`"] pub trait AnyMutRefExt<'a> { /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] fn downcast_mut<T:'static>(self) -> Option<&'a mut T>; /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[deprecated = "this function has been renamed to `downcast_mut`"] fn
<T:'static>(self) -> Option<&'a mut T> { self.downcast_mut::<T>() } } #[stable] impl<'a> AnyMutRefExt<'a> for &'a mut Any+'a { #[inline] #[unstable = "naming conventions around acquiring references may change"] fn downcast_mut<T:'static>(self) -> Option<&'a mut T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } }
as_mut
identifier_name
any.rs
// Copyright 2013-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. //! Traits for dynamic typing of any `'static` type (through runtime reflection) //! //! This module implements the `Any` trait, which enables dynamic typing //! of any `'static` type through runtime reflection. //! //! `Any` itself can be used to get a `TypeId`, and has more features when used //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and //! `as_ref` methods, to test if the contained value is of a given type, and to //! get a reference to the inner value as a type. As`&mut Any`, there is also //! the `as_mut` method, for getting a mutable reference to the inner value. //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the //! object. See the extension traits (`*Ext`) for the full details. //! //! Note that &Any is limited to testing whether a value is of a specified //! concrete type, and cannot be used to test whether a type implements a trait. //! //! # Examples //! //! Consider a situation where we want to log out a value passed to a function. //! We know the value we're working on implements Show, but we don't know its //! concrete type. We want to give special treatment to certain types: in this //! case printing out the length of String values prior to their value. //! We don't know the concrete type of our value at compile time, so we need to //! use runtime reflection instead. //! //! ```rust //! use std::fmt::Show; //! use std::any::{Any, AnyRefExt}; //! //! // Logger function for any type that implements Show. //! fn log<T: Any+Show>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to //! // output the String's length as well as its value. If not, it's a //! // different type: just print it out unadorned. //! match value_any.downcast_ref::<String>() { //! Some(as_string) => { //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { //! println!("{}", value); //! } //! } //! } //! //! // This function wants to log its parameter out prior to doing work with it. //! fn do_work<T: Show+'static>(value: &T) { //! log(value); //! //...do some other work //! } //! //! fn main() { //! let my_string = "Hello World".to_string(); //! do_work(&my_string); //! //! let my_i8: i8 = 100; //! do_work(&my_i8); //! } //! ``` #![stable] use mem::{transmute, transmute_copy}; use option::{Option, Some, None}; use raw::TraitObject; use intrinsics::TypeId; /// A type with no inhabitants #[deprecated = "this type is being removed, define a type locally if \ necessary"] pub enum Void { } /////////////////////////////////////////////////////////////////////////////// // Any trait /////////////////////////////////////////////////////////////////////////////// /// The `Any` trait is implemented by all `'static` types, and can be used for /// dynamic typing /// /// Every type with no non-`'static` references implements `Any`, so `Any` can /// be used as a trait object to emulate the effects dynamic typing. #[stable] pub trait Any: AnyPrivate {} /// An inner trait to ensure that only this module can call `get_type_id()`. pub trait AnyPrivate { /// Get the `TypeId` of `self` fn get_type_id(&self) -> TypeId; } impl<T:'static> AnyPrivate for T { fn get_type_id(&self) -> TypeId { TypeId::of::<T>() } } impl<T:'static + AnyPrivate> Any for T {} /////////////////////////////////////////////////////////////////////////////// // Extension methods for Any trait objects. // Implemented as three extension traits so that the methods can be generic. /////////////////////////////////////////////////////////////////////////////// /// Extension methods for a referenced `Any` trait object #[unstable = "this trait will not be necessary once DST lands, it will be a \ part of `impl Any`"] pub trait AnyRefExt<'a> { /// Returns true if the boxed type is the same as `T` #[stable] fn is<T:'static>(self) -> bool; /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] fn downcast_ref<T:'static>(self) -> Option<&'a T>; /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[deprecated = "this function has been renamed to `downcast_ref`"] fn as_ref<T:'static>(self) -> Option<&'a T> { self.downcast_ref::<T>() } } #[stable] impl<'a> AnyRefExt<'a> for &'a Any+'a { #[inline] #[stable] fn is<T:'static>(self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } #[inline] #[unstable = "naming conventions around acquiring references may change"] fn downcast_ref<T:'static>(self) -> Option<&'a T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } } /// Extension methods for a mutable referenced `Any` trait object #[unstable = "this trait will not be necessary once DST lands, it will be a \ part of `impl Any`"] pub trait AnyMutRefExt<'a> { /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] fn downcast_mut<T:'static>(self) -> Option<&'a mut T>; /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[deprecated = "this function has been renamed to `downcast_mut`"] fn as_mut<T:'static>(self) -> Option<&'a mut T> { self.downcast_mut::<T>() } } #[stable] impl<'a> AnyMutRefExt<'a> for &'a mut Any+'a { #[inline] #[unstable = "naming conventions around acquiring references may change"] fn downcast_mut<T:'static>(self) -> Option<&'a mut T>
}
{ if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else { None } }
identifier_body
any.rs
// Copyright 2013-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. //! Traits for dynamic typing of any `'static` type (through runtime reflection) //! //! This module implements the `Any` trait, which enables dynamic typing //! of any `'static` type through runtime reflection. //! //! `Any` itself can be used to get a `TypeId`, and has more features when used //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and //! `as_ref` methods, to test if the contained value is of a given type, and to //! get a reference to the inner value as a type. As`&mut Any`, there is also //! the `as_mut` method, for getting a mutable reference to the inner value. //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the //! object. See the extension traits (`*Ext`) for the full details. //! //! Note that &Any is limited to testing whether a value is of a specified //! concrete type, and cannot be used to test whether a type implements a trait. //! //! # Examples //! //! Consider a situation where we want to log out a value passed to a function. //! We know the value we're working on implements Show, but we don't know its //! concrete type. We want to give special treatment to certain types: in this //! case printing out the length of String values prior to their value. //! We don't know the concrete type of our value at compile time, so we need to //! use runtime reflection instead. //! //! ```rust //! use std::fmt::Show; //! use std::any::{Any, AnyRefExt}; //! //! // Logger function for any type that implements Show. //! fn log<T: Any+Show>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to //! // output the String's length as well as its value. If not, it's a //! // different type: just print it out unadorned. //! match value_any.downcast_ref::<String>() { //! Some(as_string) => { //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { //! println!("{}", value); //! } //! } //! } //! //! // This function wants to log its parameter out prior to doing work with it. //! fn do_work<T: Show+'static>(value: &T) { //! log(value); //! //...do some other work //! } //! //! fn main() { //! let my_string = "Hello World".to_string(); //! do_work(&my_string); //! //! let my_i8: i8 = 100; //! do_work(&my_i8); //! } //! ``` #![stable] use mem::{transmute, transmute_copy}; use option::{Option, Some, None}; use raw::TraitObject; use intrinsics::TypeId; /// A type with no inhabitants #[deprecated = "this type is being removed, define a type locally if \ necessary"] pub enum Void { } /////////////////////////////////////////////////////////////////////////////// // Any trait /////////////////////////////////////////////////////////////////////////////// /// The `Any` trait is implemented by all `'static` types, and can be used for /// dynamic typing /// /// Every type with no non-`'static` references implements `Any`, so `Any` can /// be used as a trait object to emulate the effects dynamic typing. #[stable] pub trait Any: AnyPrivate {} /// An inner trait to ensure that only this module can call `get_type_id()`. pub trait AnyPrivate { /// Get the `TypeId` of `self` fn get_type_id(&self) -> TypeId; } impl<T:'static> AnyPrivate for T { fn get_type_id(&self) -> TypeId { TypeId::of::<T>() } } impl<T:'static + AnyPrivate> Any for T {} /////////////////////////////////////////////////////////////////////////////// // Extension methods for Any trait objects. // Implemented as three extension traits so that the methods can be generic. /////////////////////////////////////////////////////////////////////////////// /// Extension methods for a referenced `Any` trait object #[unstable = "this trait will not be necessary once DST lands, it will be a \ part of `impl Any`"] pub trait AnyRefExt<'a> { /// Returns true if the boxed type is the same as `T` #[stable] fn is<T:'static>(self) -> bool; /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] fn downcast_ref<T:'static>(self) -> Option<&'a T>; /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[deprecated = "this function has been renamed to `downcast_ref`"] fn as_ref<T:'static>(self) -> Option<&'a T> { self.downcast_ref::<T>() } } #[stable] impl<'a> AnyRefExt<'a> for &'a Any+'a { #[inline] #[stable] fn is<T:'static>(self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } #[inline] #[unstable = "naming conventions around acquiring references may change"] fn downcast_ref<T:'static>(self) -> Option<&'a T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else
} } /// Extension methods for a mutable referenced `Any` trait object #[unstable = "this trait will not be necessary once DST lands, it will be a \ part of `impl Any`"] pub trait AnyMutRefExt<'a> { /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] fn downcast_mut<T:'static>(self) -> Option<&'a mut T>; /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[deprecated = "this function has been renamed to `downcast_mut`"] fn as_mut<T:'static>(self) -> Option<&'a mut T> { self.downcast_mut::<T>() } } #[stable] impl<'a> AnyMutRefExt<'a> for &'a mut Any+'a { #[inline] #[unstable = "naming conventions around acquiring references may change"] fn downcast_mut<T:'static>(self) -> Option<&'a mut T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } }
{ None }
conditional_block
any.rs
// Copyright 2013-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. //! Traits for dynamic typing of any `'static` type (through runtime reflection) //! //! This module implements the `Any` trait, which enables dynamic typing //! of any `'static` type through runtime reflection. //! //! `Any` itself can be used to get a `TypeId`, and has more features when used //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and //! `as_ref` methods, to test if the contained value is of a given type, and to //! get a reference to the inner value as a type. As`&mut Any`, there is also //! the `as_mut` method, for getting a mutable reference to the inner value. //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the //! object. See the extension traits (`*Ext`) for the full details. //! //! Note that &Any is limited to testing whether a value is of a specified //! concrete type, and cannot be used to test whether a type implements a trait. //! //! # Examples //! //! Consider a situation where we want to log out a value passed to a function. //! We know the value we're working on implements Show, but we don't know its //! concrete type. We want to give special treatment to certain types: in this //! case printing out the length of String values prior to their value. //! We don't know the concrete type of our value at compile time, so we need to //! use runtime reflection instead. //! //! ```rust //! use std::fmt::Show; //! use std::any::{Any, AnyRefExt}; //! //! // Logger function for any type that implements Show. //! fn log<T: Any+Show>(value: &T) { //! let value_any = value as &Any; //! //! // try to convert our value to a String. If successful, we want to //! // output the String's length as well as its value. If not, it's a //! // different type: just print it out unadorned. //! match value_any.downcast_ref::<String>() { //! Some(as_string) => { //! println!("String ({}): {}", as_string.len(), as_string); //! } //! None => { //! println!("{}", value); //! } //! } //! } //! //! // This function wants to log its parameter out prior to doing work with it. //! fn do_work<T: Show+'static>(value: &T) { //! log(value); //! //...do some other work //! } //! //! fn main() { //! let my_string = "Hello World".to_string(); //! do_work(&my_string); //! //! let my_i8: i8 = 100; //! do_work(&my_i8); //! } //! ``` #![stable] use mem::{transmute, transmute_copy}; use option::{Option, Some, None}; use raw::TraitObject; use intrinsics::TypeId; /// A type with no inhabitants #[deprecated = "this type is being removed, define a type locally if \ necessary"] pub enum Void { } /////////////////////////////////////////////////////////////////////////////// // Any trait /////////////////////////////////////////////////////////////////////////////// /// The `Any` trait is implemented by all `'static` types, and can be used for /// dynamic typing /// /// Every type with no non-`'static` references implements `Any`, so `Any` can /// be used as a trait object to emulate the effects dynamic typing. #[stable] pub trait Any: AnyPrivate {} /// An inner trait to ensure that only this module can call `get_type_id()`. pub trait AnyPrivate { /// Get the `TypeId` of `self` fn get_type_id(&self) -> TypeId; } impl<T:'static> AnyPrivate for T { fn get_type_id(&self) -> TypeId { TypeId::of::<T>() } } impl<T:'static + AnyPrivate> Any for T {} /////////////////////////////////////////////////////////////////////////////// // Extension methods for Any trait objects. // Implemented as three extension traits so that the methods can be generic. /////////////////////////////////////////////////////////////////////////////// /// Extension methods for a referenced `Any` trait object #[unstable = "this trait will not be necessary once DST lands, it will be a \ part of `impl Any`"] pub trait AnyRefExt<'a> { /// Returns true if the boxed type is the same as `T` #[stable] fn is<T:'static>(self) -> bool; /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[unstable = "naming conventions around acquiring references may change"] fn downcast_ref<T:'static>(self) -> Option<&'a T>; /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[deprecated = "this function has been renamed to `downcast_ref`"] fn as_ref<T:'static>(self) -> Option<&'a T> { self.downcast_ref::<T>() } } #[stable] impl<'a> AnyRefExt<'a> for &'a Any+'a { #[inline] #[stable] fn is<T:'static>(self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } #[inline] #[unstable = "naming conventions around acquiring references may change"] fn downcast_ref<T:'static>(self) -> Option<&'a T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } } /// Extension methods for a mutable referenced `Any` trait object #[unstable = "this trait will not be necessary once DST lands, it will be a \
#[unstable = "naming conventions around acquiring references may change"] fn downcast_mut<T:'static>(self) -> Option<&'a mut T>; /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[deprecated = "this function has been renamed to `downcast_mut`"] fn as_mut<T:'static>(self) -> Option<&'a mut T> { self.downcast_mut::<T>() } } #[stable] impl<'a> AnyMutRefExt<'a> for &'a mut Any+'a { #[inline] #[unstable = "naming conventions around acquiring references may change"] fn downcast_mut<T:'static>(self) -> Option<&'a mut T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } }
part of `impl Any`"] pub trait AnyMutRefExt<'a> { /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't.
random_line_split
unop-move-semantics.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. // Test that move restrictions are enforced on overloaded unary operations use std::ops::Not; fn move_then_borrow<T: Not<Output=T> + Clone>(x: T) { !x; x.clone(); //~ ERROR: use of moved value } fn move_borrowed<T: Not<Output=T>>(x: T, mut y: T) { let m = &x; let n = &mut y; !x; //~ ERROR: cannot move out of `x` because it is borrowed !y; //~ ERROR: cannot move out of `y` because it is borrowed use_mut(n); use_imm(m); } fn illegal_dereference<T: Not<Output=T>>(mut x: T, y: T) { let m = &mut x; let n = &y; !*m; //~ ERROR: cannot move out of borrowed content !*n; //~ ERROR: cannot move out of borrowed content use_imm(n); use_mut(m); } fn main() {} fn use_mut<T>(_: &mut T)
fn use_imm<T>(_: &T) { }
{ }
identifier_body
unop-move-semantics.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. // Test that move restrictions are enforced on overloaded unary operations use std::ops::Not; fn move_then_borrow<T: Not<Output=T> + Clone>(x: T) { !x; x.clone(); //~ ERROR: use of moved value } fn move_borrowed<T: Not<Output=T>>(x: T, mut y: T) { let m = &x; let n = &mut y; !x; //~ ERROR: cannot move out of `x` because it is borrowed !y; //~ ERROR: cannot move out of `y` because it is borrowed use_mut(n); use_imm(m); } fn illegal_dereference<T: Not<Output=T>>(mut x: T, y: T) { let m = &mut x; let n = &y;
!*m; //~ ERROR: cannot move out of borrowed content !*n; //~ ERROR: cannot move out of borrowed content use_imm(n); use_mut(m); } fn main() {} fn use_mut<T>(_: &mut T) { } fn use_imm<T>(_: &T) { }
random_line_split
unop-move-semantics.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. // Test that move restrictions are enforced on overloaded unary operations use std::ops::Not; fn move_then_borrow<T: Not<Output=T> + Clone>(x: T) { !x; x.clone(); //~ ERROR: use of moved value } fn move_borrowed<T: Not<Output=T>>(x: T, mut y: T) { let m = &x; let n = &mut y; !x; //~ ERROR: cannot move out of `x` because it is borrowed !y; //~ ERROR: cannot move out of `y` because it is borrowed use_mut(n); use_imm(m); } fn illegal_dereference<T: Not<Output=T>>(mut x: T, y: T) { let m = &mut x; let n = &y; !*m; //~ ERROR: cannot move out of borrowed content !*n; //~ ERROR: cannot move out of borrowed content use_imm(n); use_mut(m); } fn main() {} fn use_mut<T>(_: &mut T) { } fn
<T>(_: &T) { }
use_imm
identifier_name
signal-exit-status.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. // ignore-windows extern crate debug; use std::os; use std::io::process::{Command, ExitSignal, ExitStatus}; pub fn main() { let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1].as_slice() == "signal" { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } else { let status = Command::new(args[0].as_slice()).arg("signal").status().unwrap(); // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK).
match status { ExitSignal(_) if cfg!(unix) => {}, ExitStatus(0xC0000028) if cfg!(windows) => {}, _ => fail!("invalid termination (was not signalled): {:?}", status) } } }
random_line_split
signal-exit-status.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. // ignore-windows extern crate debug; use std::os; use std::io::process::{Command, ExitSignal, ExitStatus}; pub fn main()
{ let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1].as_slice() == "signal" { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } else { let status = Command::new(args[0].as_slice()).arg("signal").status().unwrap(); // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK). match status { ExitSignal(_) if cfg!(unix) => {}, ExitStatus(0xC0000028) if cfg!(windows) => {}, _ => fail!("invalid termination (was not signalled): {:?}", status) } } }
identifier_body
signal-exit-status.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. // ignore-windows extern crate debug; use std::os; use std::io::process::{Command, ExitSignal, ExitStatus}; pub fn main() { let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1].as_slice() == "signal"
else { let status = Command::new(args[0].as_slice()).arg("signal").status().unwrap(); // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK). match status { ExitSignal(_) if cfg!(unix) => {}, ExitStatus(0xC0000028) if cfg!(windows) => {}, _ => fail!("invalid termination (was not signalled): {:?}", status) } } }
{ // Raise a segfault. unsafe { *(0 as *mut int) = 0; } }
conditional_block
signal-exit-status.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. // ignore-windows extern crate debug; use std::os; use std::io::process::{Command, ExitSignal, ExitStatus}; pub fn
() { let args = os::args(); let args = args.as_slice(); if args.len() >= 2 && args[1].as_slice() == "signal" { // Raise a segfault. unsafe { *(0 as *mut int) = 0; } } else { let status = Command::new(args[0].as_slice()).arg("signal").status().unwrap(); // Windows does not have signal, so we get exit status 0xC0000028 (STATUS_BAD_STACK). match status { ExitSignal(_) if cfg!(unix) => {}, ExitStatus(0xC0000028) if cfg!(windows) => {}, _ => fail!("invalid termination (was not signalled): {:?}", status) } } }
main
identifier_name
point_bvt.rs
use na::Identity; use entities::partitioning::BVTVisitor; use point::PointQuery; use math::Point; // FIXME: add a point cost fn. /// Bounding Volume Tree visitor collecting nodes that may contain a given point. pub struct PointInterferencesCollector<'a, P: 'a, B: 'a> { point: &'a P, collector: &'a mut Vec<B> } impl<'a, P, B> PointInterferencesCollector<'a, P, B> { /// Creates a new `PointInterferencesCollector`. #[inline] pub fn new(point: &'a P, buffer: &'a mut Vec<B>) -> PointInterferencesCollector<'a, P, B> { PointInterferencesCollector { point: point, collector: buffer } } } impl<'a, P, B, BV> BVTVisitor<B, BV> for PointInterferencesCollector<'a, P, B> where P: Point, B: Clone, BV: PointQuery<P, Identity> { #[inline] fn visit_internal(&mut self, bv: &BV) -> bool { bv.contains_point(&Identity::new(), self.point) }
#[inline] fn visit_leaf(&mut self, b: &B, bv: &BV) { if bv.contains_point(&Identity::new(), self.point) { self.collector.push(b.clone()) } } }
random_line_split
point_bvt.rs
use na::Identity; use entities::partitioning::BVTVisitor; use point::PointQuery; use math::Point; // FIXME: add a point cost fn. /// Bounding Volume Tree visitor collecting nodes that may contain a given point. pub struct PointInterferencesCollector<'a, P: 'a, B: 'a> { point: &'a P, collector: &'a mut Vec<B> } impl<'a, P, B> PointInterferencesCollector<'a, P, B> { /// Creates a new `PointInterferencesCollector`. #[inline] pub fn new(point: &'a P, buffer: &'a mut Vec<B>) -> PointInterferencesCollector<'a, P, B> { PointInterferencesCollector { point: point, collector: buffer } } } impl<'a, P, B, BV> BVTVisitor<B, BV> for PointInterferencesCollector<'a, P, B> where P: Point, B: Clone, BV: PointQuery<P, Identity> { #[inline] fn visit_internal(&mut self, bv: &BV) -> bool { bv.contains_point(&Identity::new(), self.point) } #[inline] fn visit_leaf(&mut self, b: &B, bv: &BV) { if bv.contains_point(&Identity::new(), self.point)
} }
{ self.collector.push(b.clone()) }
conditional_block
point_bvt.rs
use na::Identity; use entities::partitioning::BVTVisitor; use point::PointQuery; use math::Point; // FIXME: add a point cost fn. /// Bounding Volume Tree visitor collecting nodes that may contain a given point. pub struct PointInterferencesCollector<'a, P: 'a, B: 'a> { point: &'a P, collector: &'a mut Vec<B> } impl<'a, P, B> PointInterferencesCollector<'a, P, B> { /// Creates a new `PointInterferencesCollector`. #[inline] pub fn new(point: &'a P, buffer: &'a mut Vec<B>) -> PointInterferencesCollector<'a, P, B> { PointInterferencesCollector { point: point, collector: buffer } } } impl<'a, P, B, BV> BVTVisitor<B, BV> for PointInterferencesCollector<'a, P, B> where P: Point, B: Clone, BV: PointQuery<P, Identity> { #[inline] fn visit_internal(&mut self, bv: &BV) -> bool
#[inline] fn visit_leaf(&mut self, b: &B, bv: &BV) { if bv.contains_point(&Identity::new(), self.point) { self.collector.push(b.clone()) } } }
{ bv.contains_point(&Identity::new(), self.point) }
identifier_body
point_bvt.rs
use na::Identity; use entities::partitioning::BVTVisitor; use point::PointQuery; use math::Point; // FIXME: add a point cost fn. /// Bounding Volume Tree visitor collecting nodes that may contain a given point. pub struct PointInterferencesCollector<'a, P: 'a, B: 'a> { point: &'a P, collector: &'a mut Vec<B> } impl<'a, P, B> PointInterferencesCollector<'a, P, B> { /// Creates a new `PointInterferencesCollector`. #[inline] pub fn new(point: &'a P, buffer: &'a mut Vec<B>) -> PointInterferencesCollector<'a, P, B> { PointInterferencesCollector { point: point, collector: buffer } } } impl<'a, P, B, BV> BVTVisitor<B, BV> for PointInterferencesCollector<'a, P, B> where P: Point, B: Clone, BV: PointQuery<P, Identity> { #[inline] fn visit_internal(&mut self, bv: &BV) -> bool { bv.contains_point(&Identity::new(), self.point) } #[inline] fn
(&mut self, b: &B, bv: &BV) { if bv.contains_point(&Identity::new(), self.point) { self.collector.push(b.clone()) } } }
visit_leaf
identifier_name
graph.rs
use std::vec::Vec; use gnuplot::*; /// Draws a graph with x-axis indicating the iteration number and /// y-axis showing the cost at that iteration. pub fn draw_cost_graph(fg : &mut Figure, cost_history : &Vec<f64>) { let mut x = Vec::with_capacity(cost_history.len()); for i in 0..cost_history.len() { x.push(i) } fg.axes2d() .set_aspect_ratio(Fix(1.0)) .set_x_label("Iteration", &[Rotate(0.0)]) .set_y_label("Cost", &[Rotate(90.0)]) .lines(x.iter(), cost_history.iter(), &[Color("#006633")]) .set_title("Cost Graph", &[]); } /// Draws a decision boundary at p_f(x, y) = 0 by evaluating the function /// within the supplied limits. The function in evaluated as a grid of size /// (grid_size x grid_size). pub fn draw_decision_boundary_2d(fg : &mut Figure, limits : (f64, f64, f64, f64), grid_size : usize, p_f : &Fn(f64, f64) -> f64)
fg.axes3d() .surface(z_array.iter(), grid_size, grid_size, Some((x_start, y_start, x_end, y_end)), &[]) .show_contours_custom(true, true, Linear, Fix("Decision Boundary"), [0.0f64].iter()); }
{ assert!(limits.0 < limits.2); assert!(limits.1 < limits.3); assert!(grid_size >= 1); let mut z_array : Vec<f64> = vec![]; let x_start = limits.0; let y_start = limits.1; let x_end = limits.2; let y_end = limits.3; let x_step = (x_end - x_start) / grid_size as f64; let y_step = (y_end - y_start) / grid_size as f64; for row in 0..grid_size { for col in 0..grid_size { let z = p_f(x_start + col as f64 * x_step, y_start + row as f64 * y_step); z_array.push(z); } }
identifier_body
graph.rs
use std::vec::Vec; use gnuplot::*; /// Draws a graph with x-axis indicating the iteration number and /// y-axis showing the cost at that iteration. pub fn
(fg : &mut Figure, cost_history : &Vec<f64>) { let mut x = Vec::with_capacity(cost_history.len()); for i in 0..cost_history.len() { x.push(i) } fg.axes2d() .set_aspect_ratio(Fix(1.0)) .set_x_label("Iteration", &[Rotate(0.0)]) .set_y_label("Cost", &[Rotate(90.0)]) .lines(x.iter(), cost_history.iter(), &[Color("#006633")]) .set_title("Cost Graph", &[]); } /// Draws a decision boundary at p_f(x, y) = 0 by evaluating the function /// within the supplied limits. The function in evaluated as a grid of size /// (grid_size x grid_size). pub fn draw_decision_boundary_2d(fg : &mut Figure, limits : (f64, f64, f64, f64), grid_size : usize, p_f : &Fn(f64, f64) -> f64) { assert!(limits.0 < limits.2); assert!(limits.1 < limits.3); assert!(grid_size >= 1); let mut z_array : Vec<f64> = vec![]; let x_start = limits.0; let y_start = limits.1; let x_end = limits.2; let y_end = limits.3; let x_step = (x_end - x_start) / grid_size as f64; let y_step = (y_end - y_start) / grid_size as f64; for row in 0..grid_size { for col in 0..grid_size { let z = p_f(x_start + col as f64 * x_step, y_start + row as f64 * y_step); z_array.push(z); } } fg.axes3d() .surface(z_array.iter(), grid_size, grid_size, Some((x_start, y_start, x_end, y_end)), &[]) .show_contours_custom(true, true, Linear, Fix("Decision Boundary"), [0.0f64].iter()); }
draw_cost_graph
identifier_name
graph.rs
use std::vec::Vec; use gnuplot::*; /// Draws a graph with x-axis indicating the iteration number and /// y-axis showing the cost at that iteration. pub fn draw_cost_graph(fg : &mut Figure, cost_history : &Vec<f64>) { let mut x = Vec::with_capacity(cost_history.len());
.set_aspect_ratio(Fix(1.0)) .set_x_label("Iteration", &[Rotate(0.0)]) .set_y_label("Cost", &[Rotate(90.0)]) .lines(x.iter(), cost_history.iter(), &[Color("#006633")]) .set_title("Cost Graph", &[]); } /// Draws a decision boundary at p_f(x, y) = 0 by evaluating the function /// within the supplied limits. The function in evaluated as a grid of size /// (grid_size x grid_size). pub fn draw_decision_boundary_2d(fg : &mut Figure, limits : (f64, f64, f64, f64), grid_size : usize, p_f : &Fn(f64, f64) -> f64) { assert!(limits.0 < limits.2); assert!(limits.1 < limits.3); assert!(grid_size >= 1); let mut z_array : Vec<f64> = vec![]; let x_start = limits.0; let y_start = limits.1; let x_end = limits.2; let y_end = limits.3; let x_step = (x_end - x_start) / grid_size as f64; let y_step = (y_end - y_start) / grid_size as f64; for row in 0..grid_size { for col in 0..grid_size { let z = p_f(x_start + col as f64 * x_step, y_start + row as f64 * y_step); z_array.push(z); } } fg.axes3d() .surface(z_array.iter(), grid_size, grid_size, Some((x_start, y_start, x_end, y_end)), &[]) .show_contours_custom(true, true, Linear, Fix("Decision Boundary"), [0.0f64].iter()); }
for i in 0..cost_history.len() { x.push(i) } fg.axes2d()
random_line_split
cell_renderer_text.rs
// This file was generated by gir (17af302) from gir-files (11e0e6d) // DO NOT EDIT use CellRenderer; use ffi; use glib::object::Downcast; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct CellRendererText(Object<ffi::GtkCellRendererText>): CellRenderer; match fn { get_type => || ffi::gtk_cell_renderer_text_get_type(), } } impl CellRendererText { pub fn new() -> CellRendererText { assert_initialized_main_thread!(); unsafe { CellRenderer::from_glib_none(ffi::gtk_cell_renderer_text_new()).downcast_unchecked() } } } pub trait CellRendererTextExt { fn set_fixed_height_from_font(&self, number_of_rows: i32); } impl<O: IsA<CellRendererText>> CellRendererTextExt for O { fn set_fixed_height_from_font(&self, number_of_rows: i32)
}
{ unsafe { ffi::gtk_cell_renderer_text_set_fixed_height_from_font(self.to_glib_none().0, number_of_rows); } }
identifier_body
cell_renderer_text.rs
// This file was generated by gir (17af302) from gir-files (11e0e6d) // DO NOT EDIT
use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct CellRendererText(Object<ffi::GtkCellRendererText>): CellRenderer; match fn { get_type => || ffi::gtk_cell_renderer_text_get_type(), } } impl CellRendererText { pub fn new() -> CellRendererText { assert_initialized_main_thread!(); unsafe { CellRenderer::from_glib_none(ffi::gtk_cell_renderer_text_new()).downcast_unchecked() } } } pub trait CellRendererTextExt { fn set_fixed_height_from_font(&self, number_of_rows: i32); } impl<O: IsA<CellRendererText>> CellRendererTextExt for O { fn set_fixed_height_from_font(&self, number_of_rows: i32) { unsafe { ffi::gtk_cell_renderer_text_set_fixed_height_from_font(self.to_glib_none().0, number_of_rows); } } }
use CellRenderer; use ffi; use glib::object::Downcast;
random_line_split
cell_renderer_text.rs
// This file was generated by gir (17af302) from gir-files (11e0e6d) // DO NOT EDIT use CellRenderer; use ffi; use glib::object::Downcast; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct CellRendererText(Object<ffi::GtkCellRendererText>): CellRenderer; match fn { get_type => || ffi::gtk_cell_renderer_text_get_type(), } } impl CellRendererText { pub fn new() -> CellRendererText { assert_initialized_main_thread!(); unsafe { CellRenderer::from_glib_none(ffi::gtk_cell_renderer_text_new()).downcast_unchecked() } } } pub trait CellRendererTextExt { fn set_fixed_height_from_font(&self, number_of_rows: i32); } impl<O: IsA<CellRendererText>> CellRendererTextExt for O { fn
(&self, number_of_rows: i32) { unsafe { ffi::gtk_cell_renderer_text_set_fixed_height_from_font(self.to_glib_none().0, number_of_rows); } } }
set_fixed_height_from_font
identifier_name
numeric-method-autoexport.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. // no-pretty-expanded // This file is intended to test only that methods are automatically // reachable for each numeric type, for each exported impl, with no imports // necessary. Testing the methods of the impls is done within the source // file for each numeric type. #![feature(core)] use std::ops::Add; use std::num::ToPrimitive; pub fn
() { // ints // num assert_eq!(15_isize.add(6_isize), 21_isize); assert_eq!(15_i8.add(6i8), 21_i8); assert_eq!(15_i16.add(6i16), 21_i16); assert_eq!(15_i32.add(6i32), 21_i32); assert_eq!(15_i64.add(6i64), 21_i64); // uints // num assert_eq!(15_usize.add(6_usize), 21_usize); assert_eq!(15_u8.add(6u8), 21_u8); assert_eq!(15_u16.add(6u16), 21_u16); assert_eq!(15_u32.add(6u32), 21_u32); assert_eq!(15_u64.add(6u64), 21_u64); // floats // num assert_eq!(10_f32.to_i32().unwrap(), 10); assert_eq!(10_f64.to_i32().unwrap(), 10); }
main
identifier_name
numeric-method-autoexport.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. // no-pretty-expanded // This file is intended to test only that methods are automatically // reachable for each numeric type, for each exported impl, with no imports // necessary. Testing the methods of the impls is done within the source // file for each numeric type. #![feature(core)] use std::ops::Add; use std::num::ToPrimitive; pub fn main() { // ints // num assert_eq!(15_isize.add(6_isize), 21_isize); assert_eq!(15_i8.add(6i8), 21_i8); assert_eq!(15_i16.add(6i16), 21_i16); assert_eq!(15_i32.add(6i32), 21_i32); assert_eq!(15_i64.add(6i64), 21_i64); // uints // num assert_eq!(15_usize.add(6_usize), 21_usize); assert_eq!(15_u8.add(6u8), 21_u8); assert_eq!(15_u16.add(6u16), 21_u16); assert_eq!(15_u32.add(6u32), 21_u32); assert_eq!(15_u64.add(6u64), 21_u64);
// floats // num assert_eq!(10_f32.to_i32().unwrap(), 10); assert_eq!(10_f64.to_i32().unwrap(), 10); }
random_line_split
numeric-method-autoexport.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. // no-pretty-expanded // This file is intended to test only that methods are automatically // reachable for each numeric type, for each exported impl, with no imports // necessary. Testing the methods of the impls is done within the source // file for each numeric type. #![feature(core)] use std::ops::Add; use std::num::ToPrimitive; pub fn main()
assert_eq!(10_f64.to_i32().unwrap(), 10); }
{ // ints // num assert_eq!(15_isize.add(6_isize), 21_isize); assert_eq!(15_i8.add(6i8), 21_i8); assert_eq!(15_i16.add(6i16), 21_i16); assert_eq!(15_i32.add(6i32), 21_i32); assert_eq!(15_i64.add(6i64), 21_i64); // uints // num assert_eq!(15_usize.add(6_usize), 21_usize); assert_eq!(15_u8.add(6u8), 21_u8); assert_eq!(15_u16.add(6u16), 21_u16); assert_eq!(15_u32.add(6u32), 21_u32); assert_eq!(15_u64.add(6u64), 21_u64); // floats // num assert_eq!(10_f32.to_i32().unwrap(), 10);
identifier_body
driver.rs
use libc::c_int; use std::ffi::CString; use std::ptr::null_mut; use std::sync::{Once, ONCE_INIT}; use utils::{_string, _last_null_pointer_err}; use raster::Dataset; use raster::types::GdalType; use gdal_major_object::MajorObject; use metadata::Metadata; use gdal_sys::{self, GDALDriverH, GDALMajorObjectH}; use errors::*; static START: Once = ONCE_INIT; pub fn _register_drivers() { unsafe { START.call_once(|| { gdal_sys::GDALAllRegister(); }); } } #[allow(missing_copy_implementations)] pub struct Driver { c_driver: GDALDriverH, } impl Driver { pub fn get(name: &str) -> Result<Driver> { _register_drivers(); let c_name = CString::new(name)?; let c_driver = unsafe { gdal_sys::GDALGetDriverByName(c_name.as_ptr()) }; if c_driver.is_null() { Err(_last_null_pointer_err("GDALGetDriverByName"))?; }; Ok(Driver{c_driver}) } pub unsafe fn _with_c_ptr(c_driver: GDALDriverH) -> Driver { Driver { c_driver } } pub unsafe fn _c_ptr(&self) -> GDALDriverH { self.c_driver } pub fn short_name(&self) -> String { let rv = unsafe { gdal_sys::GDALGetDriverShortName(self.c_driver) }; _string(rv) } pub fn long_name(&self) -> String { let rv = unsafe { gdal_sys::GDALGetDriverLongName(self.c_driver) }; _string(rv) } pub fn create( &self, filename: &str, size_x: isize, size_y: isize, bands: isize ) -> Result<Dataset> { self.create_with_band_type::<u8>( filename, size_x, size_y, bands, ) } pub fn create_with_band_type<T: GdalType>( &self, filename: &str, size_x: isize, size_y: isize, bands: isize, ) -> Result<Dataset> { let c_filename = CString::new(filename)?; let c_dataset = unsafe { gdal_sys::GDALCreate( self.c_driver, c_filename.as_ptr(),
size_y as c_int, bands as c_int, T::gdal_type(), null_mut() ) }; if c_dataset.is_null() { Err(_last_null_pointer_err("GDALCreate"))?; }; Ok(unsafe { Dataset::_with_c_ptr(c_dataset) }) } } impl MajorObject for Driver { unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH { self.c_driver } } impl Metadata for Driver {}
size_x as c_int,
random_line_split
driver.rs
use libc::c_int; use std::ffi::CString; use std::ptr::null_mut; use std::sync::{Once, ONCE_INIT}; use utils::{_string, _last_null_pointer_err}; use raster::Dataset; use raster::types::GdalType; use gdal_major_object::MajorObject; use metadata::Metadata; use gdal_sys::{self, GDALDriverH, GDALMajorObjectH}; use errors::*; static START: Once = ONCE_INIT; pub fn _register_drivers() { unsafe { START.call_once(|| { gdal_sys::GDALAllRegister(); }); } } #[allow(missing_copy_implementations)] pub struct
{ c_driver: GDALDriverH, } impl Driver { pub fn get(name: &str) -> Result<Driver> { _register_drivers(); let c_name = CString::new(name)?; let c_driver = unsafe { gdal_sys::GDALGetDriverByName(c_name.as_ptr()) }; if c_driver.is_null() { Err(_last_null_pointer_err("GDALGetDriverByName"))?; }; Ok(Driver{c_driver}) } pub unsafe fn _with_c_ptr(c_driver: GDALDriverH) -> Driver { Driver { c_driver } } pub unsafe fn _c_ptr(&self) -> GDALDriverH { self.c_driver } pub fn short_name(&self) -> String { let rv = unsafe { gdal_sys::GDALGetDriverShortName(self.c_driver) }; _string(rv) } pub fn long_name(&self) -> String { let rv = unsafe { gdal_sys::GDALGetDriverLongName(self.c_driver) }; _string(rv) } pub fn create( &self, filename: &str, size_x: isize, size_y: isize, bands: isize ) -> Result<Dataset> { self.create_with_band_type::<u8>( filename, size_x, size_y, bands, ) } pub fn create_with_band_type<T: GdalType>( &self, filename: &str, size_x: isize, size_y: isize, bands: isize, ) -> Result<Dataset> { let c_filename = CString::new(filename)?; let c_dataset = unsafe { gdal_sys::GDALCreate( self.c_driver, c_filename.as_ptr(), size_x as c_int, size_y as c_int, bands as c_int, T::gdal_type(), null_mut() ) }; if c_dataset.is_null() { Err(_last_null_pointer_err("GDALCreate"))?; }; Ok(unsafe { Dataset::_with_c_ptr(c_dataset) }) } } impl MajorObject for Driver { unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH { self.c_driver } } impl Metadata for Driver {}
Driver
identifier_name
driver.rs
use libc::c_int; use std::ffi::CString; use std::ptr::null_mut; use std::sync::{Once, ONCE_INIT}; use utils::{_string, _last_null_pointer_err}; use raster::Dataset; use raster::types::GdalType; use gdal_major_object::MajorObject; use metadata::Metadata; use gdal_sys::{self, GDALDriverH, GDALMajorObjectH}; use errors::*; static START: Once = ONCE_INIT; pub fn _register_drivers() { unsafe { START.call_once(|| { gdal_sys::GDALAllRegister(); }); } } #[allow(missing_copy_implementations)] pub struct Driver { c_driver: GDALDriverH, } impl Driver { pub fn get(name: &str) -> Result<Driver> { _register_drivers(); let c_name = CString::new(name)?; let c_driver = unsafe { gdal_sys::GDALGetDriverByName(c_name.as_ptr()) }; if c_driver.is_null() { Err(_last_null_pointer_err("GDALGetDriverByName"))?; }; Ok(Driver{c_driver}) } pub unsafe fn _with_c_ptr(c_driver: GDALDriverH) -> Driver { Driver { c_driver } } pub unsafe fn _c_ptr(&self) -> GDALDriverH
pub fn short_name(&self) -> String { let rv = unsafe { gdal_sys::GDALGetDriverShortName(self.c_driver) }; _string(rv) } pub fn long_name(&self) -> String { let rv = unsafe { gdal_sys::GDALGetDriverLongName(self.c_driver) }; _string(rv) } pub fn create( &self, filename: &str, size_x: isize, size_y: isize, bands: isize ) -> Result<Dataset> { self.create_with_band_type::<u8>( filename, size_x, size_y, bands, ) } pub fn create_with_band_type<T: GdalType>( &self, filename: &str, size_x: isize, size_y: isize, bands: isize, ) -> Result<Dataset> { let c_filename = CString::new(filename)?; let c_dataset = unsafe { gdal_sys::GDALCreate( self.c_driver, c_filename.as_ptr(), size_x as c_int, size_y as c_int, bands as c_int, T::gdal_type(), null_mut() ) }; if c_dataset.is_null() { Err(_last_null_pointer_err("GDALCreate"))?; }; Ok(unsafe { Dataset::_with_c_ptr(c_dataset) }) } } impl MajorObject for Driver { unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH { self.c_driver } } impl Metadata for Driver {}
{ self.c_driver }
identifier_body
driver.rs
use libc::c_int; use std::ffi::CString; use std::ptr::null_mut; use std::sync::{Once, ONCE_INIT}; use utils::{_string, _last_null_pointer_err}; use raster::Dataset; use raster::types::GdalType; use gdal_major_object::MajorObject; use metadata::Metadata; use gdal_sys::{self, GDALDriverH, GDALMajorObjectH}; use errors::*; static START: Once = ONCE_INIT; pub fn _register_drivers() { unsafe { START.call_once(|| { gdal_sys::GDALAllRegister(); }); } } #[allow(missing_copy_implementations)] pub struct Driver { c_driver: GDALDriverH, } impl Driver { pub fn get(name: &str) -> Result<Driver> { _register_drivers(); let c_name = CString::new(name)?; let c_driver = unsafe { gdal_sys::GDALGetDriverByName(c_name.as_ptr()) }; if c_driver.is_null() { Err(_last_null_pointer_err("GDALGetDriverByName"))?; }; Ok(Driver{c_driver}) } pub unsafe fn _with_c_ptr(c_driver: GDALDriverH) -> Driver { Driver { c_driver } } pub unsafe fn _c_ptr(&self) -> GDALDriverH { self.c_driver } pub fn short_name(&self) -> String { let rv = unsafe { gdal_sys::GDALGetDriverShortName(self.c_driver) }; _string(rv) } pub fn long_name(&self) -> String { let rv = unsafe { gdal_sys::GDALGetDriverLongName(self.c_driver) }; _string(rv) } pub fn create( &self, filename: &str, size_x: isize, size_y: isize, bands: isize ) -> Result<Dataset> { self.create_with_band_type::<u8>( filename, size_x, size_y, bands, ) } pub fn create_with_band_type<T: GdalType>( &self, filename: &str, size_x: isize, size_y: isize, bands: isize, ) -> Result<Dataset> { let c_filename = CString::new(filename)?; let c_dataset = unsafe { gdal_sys::GDALCreate( self.c_driver, c_filename.as_ptr(), size_x as c_int, size_y as c_int, bands as c_int, T::gdal_type(), null_mut() ) }; if c_dataset.is_null()
; Ok(unsafe { Dataset::_with_c_ptr(c_dataset) }) } } impl MajorObject for Driver { unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH { self.c_driver } } impl Metadata for Driver {}
{ Err(_last_null_pointer_err("GDALCreate"))?; }
conditional_block
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMetricsProvider; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::BackgroundSize; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::box_::VerticalAlign; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::BorderStyle; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::percentage::Percentage; pub use self::position::Position; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, TransformOrigin}; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod text; pub mod time; pub mod transform; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query
pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(#[ignore_malloc_size_of = "Arc"] Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
pub in_media_query: bool, /// The quirks mode of this context.
random_line_split
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMetricsProvider; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::BackgroundSize; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::box_::VerticalAlign; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::BorderStyle; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::percentage::Percentage; pub use self::position::Position; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, TransformOrigin}; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod text; pub mod time; pub mod transform; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au>
/// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(#[ignore_malloc_size_of = "Arc"] Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
{ self.builder.device.au_viewport_size_for_viewport_unit_resolution() }
identifier_body
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMetricsProvider; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::BackgroundSize; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::box_::VerticalAlign; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::BorderStyle; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::percentage::Percentage; pub use self::position::Position; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, TransformOrigin}; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod text; pub mod time; pub mod transform; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct
<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(#[ignore_malloc_size_of = "Arc"] Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
Context
identifier_name
mod.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/. */ //! Computed values. use {Atom, Namespace}; use context::QuirksMode; use euclid::Size2D; use font_metrics::FontMetricsProvider; use media_queries::Device; #[cfg(feature = "gecko")] use properties; use properties::{ComputedValues, LonghandId, StyleBuilder}; use rule_cache::RuleCacheConditions; #[cfg(feature = "servo")] use servo_url::ServoUrl; use std::{f32, fmt}; use std::cell::RefCell; #[cfg(feature = "servo")] use std::sync::Arc; use style_traits::ToCss; use style_traits::cursor::Cursor; use super::{CSSFloat, CSSInteger}; use super::generics::{GreaterThanOrEqualToOne, NonNegative}; use super::generics::grid::{GridLine as GenericGridLine, TrackBreadth as GenericTrackBreadth}; use super::generics::grid::{TrackSize as GenericTrackSize, TrackList as GenericTrackList}; use super::generics::grid::GridTemplateComponent as GenericGridTemplateComponent; use super::specified; pub use app_units::Au; pub use properties::animated_properties::TransitionProperty; #[cfg(feature = "gecko")] pub use self::align::{AlignItems, AlignJustifyContent, AlignJustifySelf, JustifyItems}; pub use self::angle::Angle; pub use self::background::BackgroundSize; pub use self::border::{BorderImageSlice, BorderImageWidth, BorderImageSideWidth}; pub use self::border::{BorderRadius, BorderCornerRadius, BorderSpacing}; pub use self::box_::VerticalAlign; pub use self::color::{Color, ColorPropertyValue, RGBAColor}; pub use self::effects::{BoxShadow, Filter, SimpleShadow}; pub use self::flex::FlexBasis; pub use self::image::{Gradient, GradientItem, Image, ImageLayer, LineDirection, MozImageRect}; #[cfg(feature = "gecko")] pub use self::gecko::ScrollSnapPoint; pub use self::rect::LengthOrNumberRect; pub use super::{Auto, Either, None_}; pub use super::specified::BorderStyle; pub use self::length::{CalcLengthOrPercentage, Length, LengthOrNone, LengthOrNumber, LengthOrPercentage}; pub use self::length::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone, MaxLength, MozLength}; pub use self::length::{CSSPixelLength, NonNegativeLength, NonNegativeLengthOrPercentage}; pub use self::percentage::Percentage; pub use self::position::Position; pub use self::svg::{SVGLength, SVGOpacity, SVGPaint, SVGPaintKind, SVGStrokeDashArray, SVGWidth}; pub use self::text::{InitialLetter, LetterSpacing, LineHeight, WordSpacing}; pub use self::time::Time; pub use self::transform::{TimingFunction, TransformOrigin}; #[cfg(feature = "gecko")] pub mod align; pub mod angle; pub mod background; pub mod basic_shape; pub mod border; #[path = "box.rs"] pub mod box_; pub mod color; pub mod effects; pub mod flex; pub mod font; pub mod image; #[cfg(feature = "gecko")] pub mod gecko; pub mod length; pub mod percentage; pub mod position; pub mod rect; pub mod svg; pub mod text; pub mod time; pub mod transform; /// A `Context` is all the data a specified value could ever need to compute /// itself and be transformed to a computed value. pub struct Context<'a> { /// Whether the current element is the root element. pub is_root_element: bool, /// Values accessed through this need to be in the properties "computed /// early": color, text-decoration, font-size, display, position, float, /// border-*-style, outline-style, font-family, writing-mode... pub builder: StyleBuilder<'a>, /// A cached computed system font value, for use by gecko. /// /// See properties/longhands/font.mako.rs #[cfg(feature = "gecko")] pub cached_system_font: Option<properties::longhands::system_font::ComputedSystemFont>, /// A dummy option for servo so initializing a computed::Context isn't /// painful. /// /// TODO(emilio): Make constructors for Context, and drop this. #[cfg(feature = "servo")] pub cached_system_font: Option<()>, /// A font metrics provider, used to access font metrics to implement /// font-relative units. pub font_metrics_provider: &'a FontMetricsProvider, /// Whether or not we are computing the media list in a media query pub in_media_query: bool, /// The quirks mode of this context. pub quirks_mode: QuirksMode, /// Whether this computation is being done for a SMIL animation. /// /// This is used to allow certain properties to generate out-of-range /// values, which SMIL allows. pub for_smil_animation: bool, /// The property we are computing a value for, if it is a non-inherited /// property. None if we are computed a value for an inherited property /// or not computing for a property at all (e.g. in a media query /// evaluation). pub for_non_inherited_property: Option<LonghandId>, /// The conditions to cache a rule node on the rule cache. /// /// FIXME(emilio): Drop the refcell. pub rule_cache_conditions: RefCell<&'a mut RuleCacheConditions>, } impl<'a> Context<'a> { /// Whether the current element is the root element. pub fn is_root_element(&self) -> bool { self.is_root_element } /// The current device. pub fn device(&self) -> &Device { self.builder.device } /// The current viewport size, used to resolve viewport units. pub fn viewport_size_for_viewport_unit_resolution(&self) -> Size2D<Au> { self.builder.device.au_viewport_size_for_viewport_unit_resolution() } /// The default computed style we're getting our reset style from. pub fn default_style(&self) -> &ComputedValues { self.builder.default_style() } /// The current style. pub fn style(&self) -> &StyleBuilder { &self.builder } /// Apply text-zoom if enabled. #[cfg(feature = "gecko")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { // We disable zoom for <svg:text> by unsetting the // -x-text-zoom property, which leads to a false value // in mAllowZoom if self.style().get_font().gecko.mAllowZoom { self.device().zoom_text(Au::from(size)).into() } else { size } } /// (Servo doesn't do text-zoom) #[cfg(feature = "servo")] pub fn maybe_zoom_text(&self, size: NonNegativeLength) -> NonNegativeLength { size } } /// An iterator over a slice of computed values #[derive(Clone)] pub struct ComputedVecIter<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> { cx: &'cx Context<'cx_a>, values: &'a [S], } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ComputedVecIter<'a, 'cx, 'cx_a, S> { /// Construct an iterator from a slice of specified values and a context pub fn new(cx: &'cx Context<'cx_a>, values: &'a [S]) -> Self { ComputedVecIter { cx: cx, values: values, } } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> ExactSizeIterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { fn len(&self) -> usize { self.values.len() } } impl<'a, 'cx, 'cx_a: 'cx, S: ToComputedValue + 'a> Iterator for ComputedVecIter<'a, 'cx, 'cx_a, S> { type Item = S::ComputedValue; fn next(&mut self) -> Option<Self::Item> { if let Some((next, rest)) = self.values.split_first() { let ret = next.to_computed_value(self.cx); self.values = rest; Some(ret) } else { None } } fn size_hint(&self) -> (usize, Option<usize>) { (self.values.len(), Some(self.values.len())) } } /// A trait to represent the conversion between computed and specified values. /// /// This trait is derivable with `#[derive(ToComputedValue)]`. The derived /// implementation just calls `ToComputedValue::to_computed_value` on each field /// of the passed value, or `Clone::clone` if the field is annotated with /// `#[compute(clone)]`. pub trait ToComputedValue { /// The computed value type we're going to be converted to. type ComputedValue; /// Convert a specified value to a computed value, using itself and the data /// inside the `Context`. #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue; #[inline] /// Convert a computed value to specified value form. /// /// This will be used for recascading during animation. /// Such from_computed_valued values should recompute to the same value. fn from_computed_value(computed: &Self::ComputedValue) -> Self; } impl<A, B> ToComputedValue for (A, B) where A: ToComputedValue, B: ToComputedValue, { type ComputedValue = ( <A as ToComputedValue>::ComputedValue, <B as ToComputedValue>::ComputedValue, ); #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { (self.0.to_computed_value(context), self.1.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { (A::from_computed_value(&computed.0), B::from_computed_value(&computed.1)) } } impl<T> ToComputedValue for Option<T> where T: ToComputedValue { type ComputedValue = Option<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.as_ref().map(|item| item.to_computed_value(context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.as_ref().map(T::from_computed_value) } } impl<T> ToComputedValue for Size2D<T> where T: ToComputedValue { type ComputedValue = Size2D<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Size2D::new( self.width.to_computed_value(context), self.height.to_computed_value(context), ) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Size2D::new( T::from_computed_value(&computed.width), T::from_computed_value(&computed.height), ) } } impl<T> ToComputedValue for Vec<T> where T: ToComputedValue { type ComputedValue = Vec<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect() } } impl<T> ToComputedValue for Box<T> where T: ToComputedValue { type ComputedValue = Box<<T as ToComputedValue>::ComputedValue>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { Box::new(T::to_computed_value(self, context)) } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { Box::new(T::from_computed_value(computed)) } } impl<T> ToComputedValue for Box<[T]> where T: ToComputedValue { type ComputedValue = Box<[<T as ToComputedValue>::ComputedValue]>; #[inline] fn to_computed_value(&self, context: &Context) -> Self::ComputedValue { self.iter().map(|item| item.to_computed_value(context)).collect::<Vec<_>>().into_boxed_slice() } #[inline] fn from_computed_value(computed: &Self::ComputedValue) -> Self { computed.iter().map(T::from_computed_value).collect::<Vec<_>>().into_boxed_slice() } } trivial_to_computed_value!(()); trivial_to_computed_value!(bool); trivial_to_computed_value!(f32); trivial_to_computed_value!(i32); trivial_to_computed_value!(u8); trivial_to_computed_value!(u16); trivial_to_computed_value!(u32); trivial_to_computed_value!(Atom); trivial_to_computed_value!(BorderStyle); trivial_to_computed_value!(Cursor); trivial_to_computed_value!(Namespace); trivial_to_computed_value!(String); /// A `<number>` value. pub type Number = CSSFloat; /// A wrapper of Number, but the value >= 0. pub type NonNegativeNumber = NonNegative<CSSFloat>; impl From<CSSFloat> for NonNegativeNumber { #[inline] fn from(number: CSSFloat) -> NonNegativeNumber { NonNegative::<CSSFloat>(number) } } impl From<NonNegativeNumber> for CSSFloat { #[inline] fn from(number: NonNegativeNumber) -> CSSFloat { number.0 } } /// A wrapper of Number, but the value >= 1. pub type GreaterThanOrEqualToOneNumber = GreaterThanOrEqualToOne<CSSFloat>; impl From<CSSFloat> for GreaterThanOrEqualToOneNumber { #[inline] fn from(number: CSSFloat) -> GreaterThanOrEqualToOneNumber { GreaterThanOrEqualToOne::<CSSFloat>(number) } } impl From<GreaterThanOrEqualToOneNumber> for CSSFloat { #[inline] fn from(number: GreaterThanOrEqualToOneNumber) -> CSSFloat { number.0 } } #[allow(missing_docs)] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, MallocSizeOf, PartialEq, ToCss)] pub enum NumberOrPercentage { Percentage(Percentage), Number(Number), } impl ToComputedValue for specified::NumberOrPercentage { type ComputedValue = NumberOrPercentage; #[inline] fn to_computed_value(&self, context: &Context) -> NumberOrPercentage { match *self { specified::NumberOrPercentage::Percentage(percentage) => NumberOrPercentage::Percentage(percentage.to_computed_value(context)), specified::NumberOrPercentage::Number(number) => NumberOrPercentage::Number(number.to_computed_value(context)), } } #[inline] fn from_computed_value(computed: &NumberOrPercentage) -> Self { match *computed { NumberOrPercentage::Percentage(percentage) => specified::NumberOrPercentage::Percentage(ToComputedValue::from_computed_value(&percentage)), NumberOrPercentage::Number(number) => specified::NumberOrPercentage::Number(ToComputedValue::from_computed_value(&number)), } } } /// A type used for opacity. pub type Opacity = CSSFloat; /// A `<integer>` value. pub type Integer = CSSInteger; /// <integer> | auto pub type IntegerOrAuto = Either<CSSInteger, Auto>; impl IntegerOrAuto { /// Returns the integer value if it is an integer, otherwise return /// the given value. pub fn integer_or(&self, auto_value: CSSInteger) -> CSSInteger { match *self { Either::First(n) => n, Either::Second(Auto) => auto_value, } } } /// A wrapper of Integer, but only accept a value >= 1. pub type PositiveInteger = GreaterThanOrEqualToOne<CSSInteger>; impl From<CSSInteger> for PositiveInteger { #[inline] fn from(int: CSSInteger) -> PositiveInteger { GreaterThanOrEqualToOne::<CSSInteger>(int) } } /// PositiveInteger | auto pub type PositiveIntegerOrAuto = Either<PositiveInteger, Auto>; /// <length> | <percentage> | <number> pub type LengthOrPercentageOrNumber = Either<Number, LengthOrPercentage>; /// NonNegativeLengthOrPercentage | NonNegativeNumber pub type NonNegativeLengthOrPercentageOrNumber = Either<NonNegativeNumber, NonNegativeLengthOrPercentage>; #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[derive(Clone, ComputeSquaredDistance, Copy, Debug, PartialEq)] /// A computed cliprect for clip and image-region pub struct ClipRect { pub top: Option<Length>, pub right: Option<Length>, pub bottom: Option<Length>, pub left: Option<Length>, } impl ToCss for ClipRect { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { dest.write_str("rect(")?; if let Some(top) = self.top { top.to_css(dest)?; dest.write_str(", ")?; } else
if let Some(right) = self.right { right.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(bottom) = self.bottom { bottom.to_css(dest)?; dest.write_str(", ")?; } else { dest.write_str("auto, ")?; } if let Some(left) = self.left { left.to_css(dest)?; } else { dest.write_str("auto")?; } dest.write_str(")") } } /// rect(...) | auto pub type ClipRectOrAuto = Either<ClipRect, Auto>; /// The computed value of a grid `<track-breadth>` pub type TrackBreadth = GenericTrackBreadth<LengthOrPercentage>; /// The computed value of a grid `<track-size>` pub type TrackSize = GenericTrackSize<LengthOrPercentage>; /// The computed value of a grid `<track-list>` /// (could also be `<auto-track-list>` or `<explicit-track-list>`) pub type TrackList = GenericTrackList<LengthOrPercentage, Integer>; /// The computed value of a `<grid-line>`. pub type GridLine = GenericGridLine<Integer>; /// `<grid-template-rows> | <grid-template-columns>` pub type GridTemplateComponent = GenericGridTemplateComponent<LengthOrPercentage, Integer>; impl ClipRectOrAuto { /// Return an auto (default for clip-rect and image-region) value pub fn auto() -> Self { Either::Second(Auto) } /// Check if it is auto pub fn is_auto(&self) -> bool { match *self { Either::Second(_) => true, _ => false } } } /// <color> | auto pub type ColorOrAuto = Either<Color, Auto>; /// The computed value of a CSS `url()`, resolved relative to the stylesheet URL. #[cfg(feature = "servo")] #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum ComputedUrl { /// The `url()` was invalid or it wasn't specified by the user. Invalid(#[ignore_malloc_size_of = "Arc"] Arc<String>), /// The resolved `url()` relative to the stylesheet URL. Valid(ServoUrl), } /// TODO: Properly build ComputedUrl for gecko #[cfg(feature = "gecko")] pub type ComputedUrl = specified::url::SpecifiedUrl; #[cfg(feature = "servo")] impl ComputedUrl { /// Returns the resolved url if it was valid. pub fn url(&self) -> Option<&ServoUrl> { match *self { ComputedUrl::Valid(ref url) => Some(url), _ => None, } } } #[cfg(feature = "servo")] impl ToCss for ComputedUrl { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { let string = match *self { ComputedUrl::Valid(ref url) => url.as_str(), ComputedUrl::Invalid(ref invalid_string) => invalid_string, }; dest.write_str("url(")?; string.to_css(dest)?; dest.write_str(")") } } /// <url> | <none> pub type UrlOrNone = Either<ComputedUrl, None_>;
{ dest.write_str("auto, ")?; }
conditional_block
lib.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/. #![crate_name = "lrs_user_group"] #![crate_type = "lib"] #![feature(plugin, no_std, negate_unsigned, custom_derive)] #![plugin(lrs_core_plugin)] #![no_std] extern crate lrs_base as base; extern crate lrs_arch_fns as arch_fns; extern crate lrs_io as io; extern crate lrs_buf_reader as buf_reader; extern crate lrs_fmt as fmt; extern crate lrs_str_one as str_one; extern crate lrs_str_two as str_two; extern crate lrs_cty as cty; extern crate lrs_parse as parse; extern crate lrs_file as file; extern crate lrs_vec as vec; extern crate lrs_alloc as alloc; extern crate lrs_rmo as rmo; extern crate lrs_iter as iter; use base::prelude::*; mod std { pub use vec::std::*; } use core::{mem}; use core::ptr::{memmove}; use base::error::{self}; use arch_fns::{memchr}; use file::{File}; pub mod group; pub mod user; struct LineReader<'a> { start: usize, end: usize, file: File, err: Option<&'a mut Result>, } impl<'a> LineReader<'a> {
Err(e) => { if let Some(err) = error { *err = Err(e); } LineReader { start: 0, end: 0, file: File::invalid(), err: None, } }, Ok(f) => LineReader { start: 0, end: 0, file: f, err: error, }, } } fn set_err(&mut self, e: error::Errno) { if let Some(ref mut err) = self.err { **err = Err(e); } } fn fill<'b>(&mut self, buf: &'b mut [u8]) -> &'b [u8] { loop { { // Borrow checked doesn't understand that return ends the loop. let cur: &'static [u8] = unsafe { mem::cast(&buf[self.start..self.end]) }; if let Some(pos) = memchr(cur, b'\n') { self.start += pos + 1; return &cur[..pos]; } } // No newline in the current buffer. // Move it to the left, try to read more, repeat. unsafe { let dst = buf.as_mut_ptr(); let src = dst.add(self.start); memmove(dst, src, self.end - self.start); } self.end -= self.start; self.start = 0; match self.file.read(&mut buf[self.end..]) { Err(e) => { // This can be error::Interrupted but only if the library was compiled // without the'retry' feature. The user wants to handle it himself. self.set_err(e); return &[]; }, Ok(0) => { if self.end == buf.len() { // The buffer is too small for this entry. self.set_err(error::NoMemory); } else if self.end > self.start { // Not at EOF but the buffer is not empty. The file is corrupted. self.set_err(error::InvalidSequence); } return &[]; }, Ok(n) => self.end += n, } } } }
fn new(file: &str, error: Option<&'a mut Result>) -> LineReader<'a> { match File::open_read(file) {
random_line_split
lib.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/. #![crate_name = "lrs_user_group"] #![crate_type = "lib"] #![feature(plugin, no_std, negate_unsigned, custom_derive)] #![plugin(lrs_core_plugin)] #![no_std] extern crate lrs_base as base; extern crate lrs_arch_fns as arch_fns; extern crate lrs_io as io; extern crate lrs_buf_reader as buf_reader; extern crate lrs_fmt as fmt; extern crate lrs_str_one as str_one; extern crate lrs_str_two as str_two; extern crate lrs_cty as cty; extern crate lrs_parse as parse; extern crate lrs_file as file; extern crate lrs_vec as vec; extern crate lrs_alloc as alloc; extern crate lrs_rmo as rmo; extern crate lrs_iter as iter; use base::prelude::*; mod std { pub use vec::std::*; } use core::{mem}; use core::ptr::{memmove}; use base::error::{self}; use arch_fns::{memchr}; use file::{File}; pub mod group; pub mod user; struct LineReader<'a> { start: usize, end: usize, file: File, err: Option<&'a mut Result>, } impl<'a> LineReader<'a> { fn new(file: &str, error: Option<&'a mut Result>) -> LineReader<'a>
fn set_err(&mut self, e: error::Errno) { if let Some(ref mut err) = self.err { **err = Err(e); } } fn fill<'b>(&mut self, buf: &'b mut [u8]) -> &'b [u8] { loop { { // Borrow checked doesn't understand that return ends the loop. let cur: &'static [u8] = unsafe { mem::cast(&buf[self.start..self.end]) }; if let Some(pos) = memchr(cur, b'\n') { self.start += pos + 1; return &cur[..pos]; } } // No newline in the current buffer. // Move it to the left, try to read more, repeat. unsafe { let dst = buf.as_mut_ptr(); let src = dst.add(self.start); memmove(dst, src, self.end - self.start); } self.end -= self.start; self.start = 0; match self.file.read(&mut buf[self.end..]) { Err(e) => { // This can be error::Interrupted but only if the library was compiled // without the'retry' feature. The user wants to handle it himself. self.set_err(e); return &[]; }, Ok(0) => { if self.end == buf.len() { // The buffer is too small for this entry. self.set_err(error::NoMemory); } else if self.end > self.start { // Not at EOF but the buffer is not empty. The file is corrupted. self.set_err(error::InvalidSequence); } return &[]; }, Ok(n) => self.end += n, } } } }
{ match File::open_read(file) { Err(e) => { if let Some(err) = error { *err = Err(e); } LineReader { start: 0, end: 0, file: File::invalid(), err: None, } }, Ok(f) => LineReader { start: 0, end: 0, file: f, err: error, }, } }
identifier_body
lib.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/. #![crate_name = "lrs_user_group"] #![crate_type = "lib"] #![feature(plugin, no_std, negate_unsigned, custom_derive)] #![plugin(lrs_core_plugin)] #![no_std] extern crate lrs_base as base; extern crate lrs_arch_fns as arch_fns; extern crate lrs_io as io; extern crate lrs_buf_reader as buf_reader; extern crate lrs_fmt as fmt; extern crate lrs_str_one as str_one; extern crate lrs_str_two as str_two; extern crate lrs_cty as cty; extern crate lrs_parse as parse; extern crate lrs_file as file; extern crate lrs_vec as vec; extern crate lrs_alloc as alloc; extern crate lrs_rmo as rmo; extern crate lrs_iter as iter; use base::prelude::*; mod std { pub use vec::std::*; } use core::{mem}; use core::ptr::{memmove}; use base::error::{self}; use arch_fns::{memchr}; use file::{File}; pub mod group; pub mod user; struct LineReader<'a> { start: usize, end: usize, file: File, err: Option<&'a mut Result>, } impl<'a> LineReader<'a> { fn new(file: &str, error: Option<&'a mut Result>) -> LineReader<'a> { match File::open_read(file) { Err(e) => { if let Some(err) = error { *err = Err(e); } LineReader { start: 0, end: 0, file: File::invalid(), err: None, } }, Ok(f) => LineReader { start: 0, end: 0, file: f, err: error, }, } } fn set_err(&mut self, e: error::Errno) { if let Some(ref mut err) = self.err { **err = Err(e); } } fn
<'b>(&mut self, buf: &'b mut [u8]) -> &'b [u8] { loop { { // Borrow checked doesn't understand that return ends the loop. let cur: &'static [u8] = unsafe { mem::cast(&buf[self.start..self.end]) }; if let Some(pos) = memchr(cur, b'\n') { self.start += pos + 1; return &cur[..pos]; } } // No newline in the current buffer. // Move it to the left, try to read more, repeat. unsafe { let dst = buf.as_mut_ptr(); let src = dst.add(self.start); memmove(dst, src, self.end - self.start); } self.end -= self.start; self.start = 0; match self.file.read(&mut buf[self.end..]) { Err(e) => { // This can be error::Interrupted but only if the library was compiled // without the'retry' feature. The user wants to handle it himself. self.set_err(e); return &[]; }, Ok(0) => { if self.end == buf.len() { // The buffer is too small for this entry. self.set_err(error::NoMemory); } else if self.end > self.start { // Not at EOF but the buffer is not empty. The file is corrupted. self.set_err(error::InvalidSequence); } return &[]; }, Ok(n) => self.end += n, } } } }
fill
identifier_name
instr_vrcp28ss.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn vrcp28ss_1() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM0)), operand3: Some(Direct(XMM1)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K7), broadcast: None }, &[98, 242, 125, 159, 203, 249], OperandSize::Dword)
fn vrcp28ss_2() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM3)), operand3: Some(IndirectScaledDisplaced(ESI, Eight, 1780382507, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 242, 101, 137, 203, 52, 245, 43, 123, 30, 106], OperandSize::Dword) } #[test] fn vrcp28ss_3() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM16)), operand2: Some(Direct(XMM0)), operand3: Some(Direct(XMM31)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K4), broadcast: None }, &[98, 130, 125, 156, 203, 199], OperandSize::Qword) } #[test] fn vrcp28ss_4() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM27)), operand2: Some(Direct(XMM5)), operand3: Some(IndirectScaledIndexed(RDX, RAX, Four, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 98, 85, 138, 203, 28, 130], OperandSize::Qword) }
} #[test]
random_line_split
instr_vrcp28ss.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn vrcp28ss_1() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM0)), operand3: Some(Direct(XMM1)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K7), broadcast: None }, &[98, 242, 125, 159, 203, 249], OperandSize::Dword) } #[test] fn vrcp28ss_2() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM3)), operand3: Some(IndirectScaledDisplaced(ESI, Eight, 1780382507, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 242, 101, 137, 203, 52, 245, 43, 123, 30, 106], OperandSize::Dword) } #[test] fn
() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM16)), operand2: Some(Direct(XMM0)), operand3: Some(Direct(XMM31)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K4), broadcast: None }, &[98, 130, 125, 156, 203, 199], OperandSize::Qword) } #[test] fn vrcp28ss_4() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM27)), operand2: Some(Direct(XMM5)), operand3: Some(IndirectScaledIndexed(RDX, RAX, Four, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 98, 85, 138, 203, 28, 130], OperandSize::Qword) }
vrcp28ss_3
identifier_name
instr_vrcp28ss.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn vrcp28ss_1()
#[test] fn vrcp28ss_2() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM6)), operand2: Some(Direct(XMM3)), operand3: Some(IndirectScaledDisplaced(ESI, Eight, 1780382507, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K1), broadcast: None }, &[98, 242, 101, 137, 203, 52, 245, 43, 123, 30, 106], OperandSize::Dword) } #[test] fn vrcp28ss_3() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM16)), operand2: Some(Direct(XMM0)), operand3: Some(Direct(XMM31)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K4), broadcast: None }, &[98, 130, 125, 156, 203, 199], OperandSize::Qword) } #[test] fn vrcp28ss_4() { run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM27)), operand2: Some(Direct(XMM5)), operand3: Some(IndirectScaledIndexed(RDX, RAX, Four, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K2), broadcast: None }, &[98, 98, 85, 138, 203, 28, 130], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::VRCP28SS, operand1: Some(Direct(XMM7)), operand2: Some(Direct(XMM0)), operand3: Some(Direct(XMM1)), operand4: None, lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K7), broadcast: None }, &[98, 242, 125, 159, 203, 249], OperandSize::Dword) }
identifier_body
22.rs
/* Problem 22: Names scores * * Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it * into alphabetical order. Then working out the alphabetical value for each name, multiply this * value by its alphabetical position in the list to obtain a name score. * * For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + * 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714. * * What is the total of all the name scores in the file? */ use shared::data_reader; use std::borrow::Borrow; fn main()
fn alphabetical_value<S: Borrow<str>>(name: S) -> u32 { name.borrow() .chars() .map(|chr| (chr as u8) - ('A' as u8) + 1) .fold(0, |sum, char_value| sum + char_value as u32) } fn get_name_list() -> Vec<String> { data_reader::for_path("./data/22-names.txt").collect() }
{ let mut names: Vec<String> = get_name_list(); names.sort(); let values = names.into_iter().map(alphabetical_value); let result = values.enumerate().fold(0, |sum, (index, score)| { let index = index as u32; sum + ((index + 1) * score) }); println!("{}", result); }
identifier_body
22.rs
/* Problem 22: Names scores * * Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it * into alphabetical order. Then working out the alphabetical value for each name, multiply this * value by its alphabetical position in the list to obtain a name score. * * For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + * 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714. * * What is the total of all the name scores in the file? */ use shared::data_reader; use std::borrow::Borrow; fn main() { let mut names: Vec<String> = get_name_list(); names.sort(); let values = names.into_iter().map(alphabetical_value); let result = values.enumerate().fold(0, |sum, (index, score)| { let index = index as u32; sum + ((index + 1) * score) });
println!("{}", result); } fn alphabetical_value<S: Borrow<str>>(name: S) -> u32 { name.borrow() .chars() .map(|chr| (chr as u8) - ('A' as u8) + 1) .fold(0, |sum, char_value| sum + char_value as u32) } fn get_name_list() -> Vec<String> { data_reader::for_path("./data/22-names.txt").collect() }
random_line_split
22.rs
/* Problem 22: Names scores * * Using names.txt, a 46K text file containing over five-thousand first names, begin by sorting it * into alphabetical order. Then working out the alphabetical value for each name, multiply this * value by its alphabetical position in the list to obtain a name score. * * For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + * 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714. * * What is the total of all the name scores in the file? */ use shared::data_reader; use std::borrow::Borrow; fn main() { let mut names: Vec<String> = get_name_list(); names.sort(); let values = names.into_iter().map(alphabetical_value); let result = values.enumerate().fold(0, |sum, (index, score)| { let index = index as u32; sum + ((index + 1) * score) }); println!("{}", result); } fn alphabetical_value<S: Borrow<str>>(name: S) -> u32 { name.borrow() .chars() .map(|chr| (chr as u8) - ('A' as u8) + 1) .fold(0, |sum, char_value| sum + char_value as u32) } fn
() -> Vec<String> { data_reader::for_path("./data/22-names.txt").collect() }
get_name_list
identifier_name
nested.rs
// Copyright 2013 The rust-for-real developers. For a full listing of the authors, // refer to the AUTHORS 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. /** * For more information about tasks' behaviour, please, refer to the README * under std/task. */ extern mod extra; use std::task; use extra::comm::DuplexStream; fn simple_nesting() { do task::spawn { let (parent, child) = DuplexStream::<int, int>(); child.send(0); // Using a supervised task to avoid // propagating linked failures to the // parent task in case it ends before // the child does. do task::spawn_supervised { loop { match child.try_recv() { Some(i) => child.send(i + 1), None => break } } }; loop { if parent.peek() { let start = parent.recv(); println(fmt!("%i", start)); if start == 10 { println("Counter is now 10"); break; } parent.send(start + 1); } } } } fn supervised_task() { do task::spawn { do task::spawn_supervised { // This won't make the parent // task fail.
fn try_task() { // This task fails but won't make the caller // task fail, instead, it'll return an error result. let failure: Result<(), ()> = do task::try { fail!("BAAAAAAD"); }; assert!(failure.is_err()); // This task won't fail and will return a ~str let success: Result<~str, ()> = do task::try { ~"Yo, you know how to do things" }; assert!(success.is_ok()); println(success.unwrap()); } fn main() { simple_nesting(); supervised_task(); try_task(); }
fail!() } } }
random_line_split
nested.rs
// Copyright 2013 The rust-for-real developers. For a full listing of the authors, // refer to the AUTHORS 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. /** * For more information about tasks' behaviour, please, refer to the README * under std/task. */ extern mod extra; use std::task; use extra::comm::DuplexStream; fn simple_nesting() { do task::spawn { let (parent, child) = DuplexStream::<int, int>(); child.send(0); // Using a supervised task to avoid // propagating linked failures to the // parent task in case it ends before // the child does. do task::spawn_supervised { loop { match child.try_recv() { Some(i) => child.send(i + 1), None => break } } }; loop { if parent.peek() { let start = parent.recv(); println(fmt!("%i", start)); if start == 10 { println("Counter is now 10"); break; } parent.send(start + 1); } } } } fn supervised_task() { do task::spawn { do task::spawn_supervised { // This won't make the parent // task fail. fail!() } } } fn try_task()
; assert!(failure.is_err()); // This task won't fail and will return a ~str let success: Result<~str, ()> = do task::try { ~"Yo, you know how to do things" }; assert!(success.is_ok()); println(success.unwrap()); } fn main() { simple_nesting(); supervised_task(); try_task(); }
{ // This task fails but won't make the caller // task fail, instead, it'll return an error result. let failure: Result<(), ()> = do task::try { fail!("BAAAAAAD"); }
identifier_body
nested.rs
// Copyright 2013 The rust-for-real developers. For a full listing of the authors, // refer to the AUTHORS 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. /** * For more information about tasks' behaviour, please, refer to the README * under std/task. */ extern mod extra; use std::task; use extra::comm::DuplexStream; fn
() { do task::spawn { let (parent, child) = DuplexStream::<int, int>(); child.send(0); // Using a supervised task to avoid // propagating linked failures to the // parent task in case it ends before // the child does. do task::spawn_supervised { loop { match child.try_recv() { Some(i) => child.send(i + 1), None => break } } }; loop { if parent.peek() { let start = parent.recv(); println(fmt!("%i", start)); if start == 10 { println("Counter is now 10"); break; } parent.send(start + 1); } } } } fn supervised_task() { do task::spawn { do task::spawn_supervised { // This won't make the parent // task fail. fail!() } } } fn try_task() { // This task fails but won't make the caller // task fail, instead, it'll return an error result. let failure: Result<(), ()> = do task::try { fail!("BAAAAAAD"); }; assert!(failure.is_err()); // This task won't fail and will return a ~str let success: Result<~str, ()> = do task::try { ~"Yo, you know how to do things" }; assert!(success.is_ok()); println(success.unwrap()); } fn main() { simple_nesting(); supervised_task(); try_task(); }
simple_nesting
identifier_name
data_dao_testing.rs
extern crate proton_cli; use proton_cli::dao::DataDao; use proton_cli::error::Error; /// Implementation of DataDao for testing purposes. Uses given functions to return values. /// Functions are boxed so their sizes are known (pointers). /// The general naming convention used is trait_function_name_fn, for all trait functions. /// &str references are converted to Strings so we don't have to deal with lifetime headaches (bookdude13 tried on 12/25/16) #[allow(dead_code)] pub struct DataDaoTesting { pub new_data_default_fn: Box<Fn(u32, Vec<u32>, Vec<u16>) -> Result<(), Error>>, pub new_data_fn: Box<Fn(u32, u32, Vec<u16>) -> Result<(), Error>>, pub get_data_fn: Box<Fn(u32, u32) -> Result<Vec<u16>, Error>>, pub update_data_fn: Box<Fn(u32, u32, Vec<u16>) -> Result<(), Error>> } impl DataDaoTesting { /// Creates a new DataDaoTesting struct with all functions set to return Error::TodoErr #[allow(dead_code)] pub fn new() -> DataDaoTesting { DataDaoTesting { new_data_default_fn: Box::new(|_, _, _| -> Result<(), Error> { Err(Error::TodoErr) }), new_data_fn: Box::new(|_, _, _| -> Result<(), Error> { Err(Error::TodoErr) }), get_data_fn: Box::new(|_, _| -> Result<Vec<u16>, Error> { Err(Error::TodoErr) }), update_data_fn: Box::new(|_, _, _| -> Result<(), Error> { Err(Error::TodoErr) }), } } } /// The Dao implementation simply calls the corresponding stored function impl DataDao for DataDaoTesting { fn new_data_default( &self, seqid: u32, chan_ids: Vec<u32>, default_data: Vec<u16> ) -> Result<(), Error>
fn new_data<'a>( &'a self, seqid: u32, chanid: u32, new_data: &'a Vec<u16> ) -> Result<(), Error> { (self.new_data_fn)(seqid, chanid, new_data.to_owned()) } fn get_data(&self, seqid: u32, chanid: u32) -> Result<Vec<u16>, Error> { (self.get_data_fn)(seqid, chanid) } fn update_data<'a>(&'a self, seqid: u32, chanid: u32, new_data: &'a Vec<u16>) -> Result<(), Error> { (self.update_data_fn)(seqid, chanid, new_data.to_owned()) } }
{ (self.new_data_default_fn)(seqid, chan_ids, default_data) }
identifier_body
data_dao_testing.rs
extern crate proton_cli; use proton_cli::dao::DataDao; use proton_cli::error::Error; /// Implementation of DataDao for testing purposes. Uses given functions to return values. /// Functions are boxed so their sizes are known (pointers). /// The general naming convention used is trait_function_name_fn, for all trait functions. /// &str references are converted to Strings so we don't have to deal with lifetime headaches (bookdude13 tried on 12/25/16) #[allow(dead_code)] pub struct
{ pub new_data_default_fn: Box<Fn(u32, Vec<u32>, Vec<u16>) -> Result<(), Error>>, pub new_data_fn: Box<Fn(u32, u32, Vec<u16>) -> Result<(), Error>>, pub get_data_fn: Box<Fn(u32, u32) -> Result<Vec<u16>, Error>>, pub update_data_fn: Box<Fn(u32, u32, Vec<u16>) -> Result<(), Error>> } impl DataDaoTesting { /// Creates a new DataDaoTesting struct with all functions set to return Error::TodoErr #[allow(dead_code)] pub fn new() -> DataDaoTesting { DataDaoTesting { new_data_default_fn: Box::new(|_, _, _| -> Result<(), Error> { Err(Error::TodoErr) }), new_data_fn: Box::new(|_, _, _| -> Result<(), Error> { Err(Error::TodoErr) }), get_data_fn: Box::new(|_, _| -> Result<Vec<u16>, Error> { Err(Error::TodoErr) }), update_data_fn: Box::new(|_, _, _| -> Result<(), Error> { Err(Error::TodoErr) }), } } } /// The Dao implementation simply calls the corresponding stored function impl DataDao for DataDaoTesting { fn new_data_default( &self, seqid: u32, chan_ids: Vec<u32>, default_data: Vec<u16> ) -> Result<(), Error> { (self.new_data_default_fn)(seqid, chan_ids, default_data) } fn new_data<'a>( &'a self, seqid: u32, chanid: u32, new_data: &'a Vec<u16> ) -> Result<(), Error> { (self.new_data_fn)(seqid, chanid, new_data.to_owned()) } fn get_data(&self, seqid: u32, chanid: u32) -> Result<Vec<u16>, Error> { (self.get_data_fn)(seqid, chanid) } fn update_data<'a>(&'a self, seqid: u32, chanid: u32, new_data: &'a Vec<u16>) -> Result<(), Error> { (self.update_data_fn)(seqid, chanid, new_data.to_owned()) } }
DataDaoTesting
identifier_name
data_dao_testing.rs
extern crate proton_cli; use proton_cli::dao::DataDao; use proton_cli::error::Error; /// Implementation of DataDao for testing purposes. Uses given functions to return values. /// Functions are boxed so their sizes are known (pointers). /// The general naming convention used is trait_function_name_fn, for all trait functions. /// &str references are converted to Strings so we don't have to deal with lifetime headaches (bookdude13 tried on 12/25/16) #[allow(dead_code)] pub struct DataDaoTesting { pub new_data_default_fn: Box<Fn(u32, Vec<u32>, Vec<u16>) -> Result<(), Error>>, pub new_data_fn: Box<Fn(u32, u32, Vec<u16>) -> Result<(), Error>>, pub get_data_fn: Box<Fn(u32, u32) -> Result<Vec<u16>, Error>>, pub update_data_fn: Box<Fn(u32, u32, Vec<u16>) -> Result<(), Error>> } impl DataDaoTesting { /// Creates a new DataDaoTesting struct with all functions set to return Error::TodoErr #[allow(dead_code)] pub fn new() -> DataDaoTesting { DataDaoTesting { new_data_default_fn: Box::new(|_, _, _| -> Result<(), Error> { Err(Error::TodoErr) }), new_data_fn: Box::new(|_, _, _| -> Result<(), Error> { Err(Error::TodoErr) }), get_data_fn: Box::new(|_, _| -> Result<Vec<u16>, Error> { Err(Error::TodoErr) }), update_data_fn: Box::new(|_, _, _| -> Result<(), Error> { Err(Error::TodoErr) }), } } } /// The Dao implementation simply calls the corresponding stored function impl DataDao for DataDaoTesting { fn new_data_default( &self, seqid: u32, chan_ids: Vec<u32>, default_data: Vec<u16> ) -> Result<(), Error> { (self.new_data_default_fn)(seqid, chan_ids, default_data) } fn new_data<'a>( &'a self, seqid: u32, chanid: u32,
) -> Result<(), Error> { (self.new_data_fn)(seqid, chanid, new_data.to_owned()) } fn get_data(&self, seqid: u32, chanid: u32) -> Result<Vec<u16>, Error> { (self.get_data_fn)(seqid, chanid) } fn update_data<'a>(&'a self, seqid: u32, chanid: u32, new_data: &'a Vec<u16>) -> Result<(), Error> { (self.update_data_fn)(seqid, chanid, new_data.to_owned()) } }
new_data: &'a Vec<u16>
random_line_split
wrapper.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::reflector::DomObject; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::bindings::trace::JSTraceable; use dom::webglrenderingcontext::WebGLRenderingContext; use js::jsapi::JSObject; use malloc_size_of::MallocSizeOf; use std::any::Any; use std::ptr::NonNull; use super::{WebGLExtension, WebGLExtensions, WebGLExtensionSpec}; /// Trait used internally by WebGLExtensions to store and /// handle the different WebGL extensions in a common list. pub trait WebGLExtensionWrapper: JSTraceable + MallocSizeOf { fn instance_or_init(&self, ctx: &WebGLRenderingContext, ext: &WebGLExtensions) -> NonNull<JSObject>; fn spec(&self) -> WebGLExtensionSpec; fn is_supported(&self, &WebGLExtensions) -> bool; fn is_enabled(&self) -> bool; fn enable(&self, ext: &WebGLExtensions); fn name(&self) -> &'static str; fn as_any(&self) -> &Any; } #[must_root] #[derive(JSTraceable, MallocSizeOf)] pub struct TypedWebGLExtensionWrapper<T: WebGLExtension> { extension: MutNullableDom<T::Extension> } /// Typed WebGL Extension implementation. /// Exposes the exact MutNullableDom<DOMObject> type defined by the extension. impl<T: WebGLExtension> TypedWebGLExtensionWrapper<T> { pub fn new() -> TypedWebGLExtensionWrapper<T> { TypedWebGLExtensionWrapper { extension: MutNullableDom::new(None) } } } impl<T> WebGLExtensionWrapper for TypedWebGLExtensionWrapper<T> where T: WebGLExtension + JSTraceable + MallocSizeOf +'static { #[allow(unsafe_code)] fn instance_or_init(&self, ctx: &WebGLRenderingContext, ext: &WebGLExtensions) -> NonNull<JSObject> { let mut enabled = true; let extension = self.extension.or_init(|| { enabled = false; T::new(ctx) }); if!enabled
unsafe { NonNull::new_unchecked(extension.reflector().get_jsobject().get()) } } fn spec(&self) -> WebGLExtensionSpec { T::spec() } fn is_supported(&self, ext: &WebGLExtensions) -> bool { self.is_enabled() || T::is_supported(ext) } fn is_enabled(&self) -> bool { self.extension.get().is_some() } fn enable(&self, ext: &WebGLExtensions) { T::enable(ext); } fn name(&self) -> &'static str { T::name() } fn as_any<'a>(&'a self) -> &'a Any { self } } impl<T> TypedWebGLExtensionWrapper<T> where T: WebGLExtension + JSTraceable + MallocSizeOf +'static { pub fn dom_object(&self) -> Option<DomRoot<T::Extension>> { self.extension.get() } }
{ self.enable(ext); }
conditional_block
wrapper.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::reflector::DomObject; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::bindings::trace::JSTraceable; use dom::webglrenderingcontext::WebGLRenderingContext; use js::jsapi::JSObject; use malloc_size_of::MallocSizeOf; use std::any::Any; use std::ptr::NonNull; use super::{WebGLExtension, WebGLExtensions, WebGLExtensionSpec}; /// Trait used internally by WebGLExtensions to store and /// handle the different WebGL extensions in a common list. pub trait WebGLExtensionWrapper: JSTraceable + MallocSizeOf { fn instance_or_init(&self, ctx: &WebGLRenderingContext, ext: &WebGLExtensions) -> NonNull<JSObject>; fn spec(&self) -> WebGLExtensionSpec; fn is_supported(&self, &WebGLExtensions) -> bool; fn is_enabled(&self) -> bool; fn enable(&self, ext: &WebGLExtensions); fn name(&self) -> &'static str; fn as_any(&self) -> &Any; } #[must_root] #[derive(JSTraceable, MallocSizeOf)] pub struct TypedWebGLExtensionWrapper<T: WebGLExtension> { extension: MutNullableDom<T::Extension> } /// Typed WebGL Extension implementation. /// Exposes the exact MutNullableDom<DOMObject> type defined by the extension. impl<T: WebGLExtension> TypedWebGLExtensionWrapper<T> { pub fn new() -> TypedWebGLExtensionWrapper<T> { TypedWebGLExtensionWrapper { extension: MutNullableDom::new(None) } } } impl<T> WebGLExtensionWrapper for TypedWebGLExtensionWrapper<T> where T: WebGLExtension + JSTraceable + MallocSizeOf +'static { #[allow(unsafe_code)] fn instance_or_init(&self, ctx: &WebGLRenderingContext, ext: &WebGLExtensions) -> NonNull<JSObject> { let mut enabled = true; let extension = self.extension.or_init(|| { enabled = false; T::new(ctx) }); if!enabled { self.enable(ext); } unsafe { NonNull::new_unchecked(extension.reflector().get_jsobject().get()) } } fn spec(&self) -> WebGLExtensionSpec { T::spec() } fn is_supported(&self, ext: &WebGLExtensions) -> bool { self.is_enabled() || T::is_supported(ext) } fn is_enabled(&self) -> bool { self.extension.get().is_some() } fn enable(&self, ext: &WebGLExtensions) { T::enable(ext); } fn name(&self) -> &'static str { T::name() } fn as_any<'a>(&'a self) -> &'a Any { self } } impl<T> TypedWebGLExtensionWrapper<T> where T: WebGLExtension + JSTraceable + MallocSizeOf +'static { pub fn
(&self) -> Option<DomRoot<T::Extension>> { self.extension.get() } }
dom_object
identifier_name
wrapper.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::reflector::DomObject; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::bindings::trace::JSTraceable; use dom::webglrenderingcontext::WebGLRenderingContext; use js::jsapi::JSObject; use malloc_size_of::MallocSizeOf; use std::any::Any; use std::ptr::NonNull; use super::{WebGLExtension, WebGLExtensions, WebGLExtensionSpec}; /// Trait used internally by WebGLExtensions to store and /// handle the different WebGL extensions in a common list. pub trait WebGLExtensionWrapper: JSTraceable + MallocSizeOf { fn instance_or_init(&self, ctx: &WebGLRenderingContext, ext: &WebGLExtensions) -> NonNull<JSObject>; fn spec(&self) -> WebGLExtensionSpec; fn is_supported(&self, &WebGLExtensions) -> bool; fn is_enabled(&self) -> bool; fn enable(&self, ext: &WebGLExtensions); fn name(&self) -> &'static str; fn as_any(&self) -> &Any; } #[must_root] #[derive(JSTraceable, MallocSizeOf)] pub struct TypedWebGLExtensionWrapper<T: WebGLExtension> { extension: MutNullableDom<T::Extension> } /// Typed WebGL Extension implementation. /// Exposes the exact MutNullableDom<DOMObject> type defined by the extension. impl<T: WebGLExtension> TypedWebGLExtensionWrapper<T> { pub fn new() -> TypedWebGLExtensionWrapper<T> { TypedWebGLExtensionWrapper { extension: MutNullableDom::new(None) } } } impl<T> WebGLExtensionWrapper for TypedWebGLExtensionWrapper<T> where T: WebGLExtension + JSTraceable + MallocSizeOf +'static { #[allow(unsafe_code)] fn instance_or_init(&self, ctx: &WebGLRenderingContext, ext: &WebGLExtensions) -> NonNull<JSObject> { let mut enabled = true; let extension = self.extension.or_init(|| { enabled = false; T::new(ctx) }); if!enabled { self.enable(ext); } unsafe { NonNull::new_unchecked(extension.reflector().get_jsobject().get()) } } fn spec(&self) -> WebGLExtensionSpec { T::spec() } fn is_supported(&self, ext: &WebGLExtensions) -> bool { self.is_enabled() || T::is_supported(ext)
self.extension.get().is_some() } fn enable(&self, ext: &WebGLExtensions) { T::enable(ext); } fn name(&self) -> &'static str { T::name() } fn as_any<'a>(&'a self) -> &'a Any { self } } impl<T> TypedWebGLExtensionWrapper<T> where T: WebGLExtension + JSTraceable + MallocSizeOf +'static { pub fn dom_object(&self) -> Option<DomRoot<T::Extension>> { self.extension.get() } }
} fn is_enabled(&self) -> bool {
random_line_split
hybrid_expect.rs
endogenous Y, ZI, ZPAI, ZY, I, PAI, R exogenous EI "monetary policy shock",EPAI "Cost push shock",EY "IS shock" parameters beta_lag "$\beta_{lag}$", beta_lead "$\beta_{lead}$", beta_r "$\beta_{r}$", gam_lag "$\gamma_{lag}$", gam_y "$\gamma_{y}$", lamb_lag "$\lambda_{lag}$", lamb_lead "$\lambda_{lead}$", lamb_y "$\lambda_{y}$", rhoi "$\rho_{i}$", rhopai "$\rho_{\pi}$", rhoy "$\rho_{y}$", siggdp "$\sigma_{gdp}$", sigi "$\sigma_{i}$", sigpai "$\sigma_{\pi}$", sigy "$\sigma_{y}$" parameters hbe_lambda hbe_w model Y=beta_lag*Y(-1)+beta_lead*Y(+1)-beta_r*R(-1)+ZY; PAI=lamb_lag*PAI(-1)+lamb_lead*PAI(+1)+lamb_y*Y(-1)+ZPAI; I=gam_lag*I(-1)+(1-gam_lag)*(PAI(+4)+gam_y*Y)+ZI; R=I-PAI(+1); ZI=rhoi*ZI(-1)+sigi*EI; ZPAI=rhopai*ZPAI(-1)+sigpai*EPAI; ZY=rhoy*ZY(-1)+sigy*EY; parameterization; beta_lag ,0.0000; beta_lead ,0.9900; beta_r ,0.1000; gam_lag ,0.6000;
rhoi ,0.0000; rhopai ,0.0000; rhoy ,0.0000; siggdp ,0.5000; sigi ,0.5000; sigpai ,0.5000; sigy ,0.5000; hbe_lambda ,0.3000; % weight on current relative to past in backward-looking expectations hbe_w ,0.3000; % weight on backward-looking expectations in "total" expectations
gam_y ,0.5000; lamb_lag ,0.0000; lamb_lead ,0.9900; lamb_y ,0.0500;
random_line_split
slice.rs
//! Slices //! //! See `Slice`-structure documentation for more information on this module. use hal::{handle, buffer}; use hal::{Primitive, Backend, VertexCount}; use hal::command::InstanceParams; use hal::device::Device; use hal::memory::Bind; use format::Format; use pso; /// A `Slice` dictates in which and in what order vertices get processed. It is required for /// processing a PSO. /// /// # Overview /// A `Slice` in gfx has a different meaning from the term slice as employed more broadly in rust (`&[T]`). /// /// A `Slice` object in essence dictates in what order the vertices in a `VertexBuffer` get /// processed. To do this, it contains an internal index-buffer. This `Buffer` is a list of /// indices into this `VertexBuffer` (vertex-index). A vertex-index of 0 represents the first /// vertex in the `VertexBuffer`, a vertex-index of 1 represents the second, 2 represents the /// third, and so on. The vertex-indices in the index-buffer are read in order; every vertex-index /// tells the pipeline which vertex to process next. /// /// Because the same index can re-appear multiple times, duplicate-vertices can be avoided. For /// instance, if you want to draw a square, you need two triangles, and thus six vertices. Because /// the same index can reappear multiple times, this means we can instead use 4 vertices, and 6 /// vertex-indices. /// /// This index-buffer has a few variants. See the `IndexBuffer` documentation for a detailed /// description. /// /// The `start` and `end` fields say where in the index-buffer to start and stop reading. /// Setting `start` to 0, and `end` to the length of the index-buffer, will cause the entire /// index-buffer to be processed. The `base_vertex` dictates the index of the first vertex /// in the `VertexBuffer`. This essentially moves the the start of the `VertexBuffer`, to the /// vertex with this index. /// /// # Construction & Handling /// The `Slice` structure can be constructed automatically when using a `Device` to create a /// vertex buffer. If needed, it can also be created manually. /// /// A `Slice` is required to process a PSO, as it contains the needed information on in what order /// to draw which vertices. As such, every `draw` call on an `Encoder` requires a `Slice`. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Slice<B: Backend> { /// The start index of the index-buffer. Processing will start at this location in the /// index-buffer. pub start: VertexCount, /// The end index in the index-buffer. Processing will stop at this location (exclusive) in /// the index buffer. pub end: VertexCount, /// This is the index of the first vertex in the `VertexBuffer`. This value will be added to /// every index in the index-buffer, effectively moving the start of the `VertexBuffer` to this /// base-vertex. pub base_vertex: VertexCount, /// Instancing configuration. pub instances: Option<InstanceParams>, /// Represents the type of index-buffer used. pub buffer: IndexBuffer<B>, } impl<B: Backend> Slice<B> { /// Creates a new `Slice` to match the supplied vertex buffer, from start to end, in order. pub fn new_match_vertex_buffer<V>(vbuf: &handle::Buffer<B, V>) -> Self where V: pso::buffer::Structure<Format> { Slice { start: 0, end: vbuf.len() as u32, base_vertex: 0, instances: None, buffer: IndexBuffer::Auto, } } /// Calculates the number of primitives of the specified type in this `Slice`. pub fn get_prim_count(&self, prim: Primitive) -> u32 { use hal::Primitive as p; let nv = (self.end - self.start) as u32; match prim { p::PointList => nv, p::LineList => nv / 2, p::LineStrip => (nv-1), p::TriangleList => nv / 3, p::TriangleStrip => (nv-2) / 3, p::LineListAdjacency => nv / 4, p::LineStripAdjacency => (nv-3), p::TriangleListAdjacency => nv / 6, p::TriangleStripAdjacency => (nv-4) / 2, p::PatchList(num) => nv / (num as u32), } } /// Divides one slice into two at an index. /// /// The first will contain the range in the index-buffer [self.start, mid) (excluding the index mid itself) and the /// second will contain the range [mid, self.end). pub fn split_at(&self, mid: VertexCount) -> (Self, Self) { let mut first = self.clone(); let mut second = self.clone(); first.end = mid; second.start = mid; (first, second) } } /// Type of index-buffer used in a Slice. /// /// The `Auto` variant represents a hypothetical index-buffer from 0 to infinity. In other words, /// all vertices get processed in order. Do note that the `Slice`'s `start` and `end` restrictions /// still apply for this variant. To render every vertex in the `VertexBuffer`, you would set /// `start` to 0, and `end` to the `VertexBuffer`'s length. /// /// The `Index*` variants represent an actual `Buffer` with a list of vertex-indices. The numeric /// suffix specifies the amount of bits to use per index. Each of these also contains a /// base-vertex. This is the index of the first vertex in the `VertexBuffer`. This value will be /// added to every index in the index-buffer, effectively moving the start of the `VertexBuffer` to /// this base-vertex. /// /// # Construction & Handling /// A `IndexBuffer` can be constructed using the `IntoIndexBuffer` trait, from either a slice or a /// `Buffer` of integers, using a device. /// /// An `IndexBuffer` is exclusively used to create `Slice`s. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum IndexBuffer<B: Backend> { /// Represents a hypothetical index-buffer from 0 to infinity. In other words, all vertices /// get processed in order. Auto, /// An index-buffer with unsigned 16 bit indices. Index16(handle::Buffer<B, u16>), /// An index-buffer with unsigned 32 bit indices. Index32(handle::Buffer<B, u32>), } impl<B: Backend> Default for IndexBuffer<B> { fn default() -> Self
} /// A helper trait to create `IndexBuffers` from different kinds of data. pub trait IntoIndexBuffer<B: Backend> { /// Turns self into an `IndexBuffer`. fn into_index_buffer<F: Device<B> +?Sized>(self, device: &mut F) -> IndexBuffer<B>; } impl<B: Backend> IntoIndexBuffer<B> for IndexBuffer<B> { fn into_index_buffer<F: Device<B> +?Sized>(self, _: &mut F) -> IndexBuffer<B> { self } } impl<B: Backend> IntoIndexBuffer<B> for () { fn into_index_buffer<F: Device<B> +?Sized>(self, _: &mut F) -> IndexBuffer<B> { IndexBuffer::Auto } } macro_rules! impl_index_buffer { ($prim_ty:ty, $buf_ty:ident) => ( impl<B: Backend> IntoIndexBuffer<B> for handle::Buffer<B, $prim_ty> { fn into_index_buffer<F: Device<B> +?Sized>(self, _: &mut F) -> IndexBuffer<B> { IndexBuffer::$buf_ty(self) } } impl<'s, B: Backend> IntoIndexBuffer<B> for &'s [$prim_ty] { fn into_index_buffer<F: Device<B> +?Sized>(self, device: &mut F) -> IndexBuffer<B> { device.create_buffer_immutable(self, buffer::Role::Index, Bind::empty()) .unwrap() .into_index_buffer(device) } } ) } impl_index_buffer!(u16, Index16); impl_index_buffer!(u32, Index32);
{ IndexBuffer::Auto }
identifier_body
slice.rs
//! Slices //! //! See `Slice`-structure documentation for more information on this module. use hal::{handle, buffer}; use hal::{Primitive, Backend, VertexCount}; use hal::command::InstanceParams; use hal::device::Device; use hal::memory::Bind; use format::Format; use pso;
/// # Overview /// A `Slice` in gfx has a different meaning from the term slice as employed more broadly in rust (`&[T]`). /// /// A `Slice` object in essence dictates in what order the vertices in a `VertexBuffer` get /// processed. To do this, it contains an internal index-buffer. This `Buffer` is a list of /// indices into this `VertexBuffer` (vertex-index). A vertex-index of 0 represents the first /// vertex in the `VertexBuffer`, a vertex-index of 1 represents the second, 2 represents the /// third, and so on. The vertex-indices in the index-buffer are read in order; every vertex-index /// tells the pipeline which vertex to process next. /// /// Because the same index can re-appear multiple times, duplicate-vertices can be avoided. For /// instance, if you want to draw a square, you need two triangles, and thus six vertices. Because /// the same index can reappear multiple times, this means we can instead use 4 vertices, and 6 /// vertex-indices. /// /// This index-buffer has a few variants. See the `IndexBuffer` documentation for a detailed /// description. /// /// The `start` and `end` fields say where in the index-buffer to start and stop reading. /// Setting `start` to 0, and `end` to the length of the index-buffer, will cause the entire /// index-buffer to be processed. The `base_vertex` dictates the index of the first vertex /// in the `VertexBuffer`. This essentially moves the the start of the `VertexBuffer`, to the /// vertex with this index. /// /// # Construction & Handling /// The `Slice` structure can be constructed automatically when using a `Device` to create a /// vertex buffer. If needed, it can also be created manually. /// /// A `Slice` is required to process a PSO, as it contains the needed information on in what order /// to draw which vertices. As such, every `draw` call on an `Encoder` requires a `Slice`. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Slice<B: Backend> { /// The start index of the index-buffer. Processing will start at this location in the /// index-buffer. pub start: VertexCount, /// The end index in the index-buffer. Processing will stop at this location (exclusive) in /// the index buffer. pub end: VertexCount, /// This is the index of the first vertex in the `VertexBuffer`. This value will be added to /// every index in the index-buffer, effectively moving the start of the `VertexBuffer` to this /// base-vertex. pub base_vertex: VertexCount, /// Instancing configuration. pub instances: Option<InstanceParams>, /// Represents the type of index-buffer used. pub buffer: IndexBuffer<B>, } impl<B: Backend> Slice<B> { /// Creates a new `Slice` to match the supplied vertex buffer, from start to end, in order. pub fn new_match_vertex_buffer<V>(vbuf: &handle::Buffer<B, V>) -> Self where V: pso::buffer::Structure<Format> { Slice { start: 0, end: vbuf.len() as u32, base_vertex: 0, instances: None, buffer: IndexBuffer::Auto, } } /// Calculates the number of primitives of the specified type in this `Slice`. pub fn get_prim_count(&self, prim: Primitive) -> u32 { use hal::Primitive as p; let nv = (self.end - self.start) as u32; match prim { p::PointList => nv, p::LineList => nv / 2, p::LineStrip => (nv-1), p::TriangleList => nv / 3, p::TriangleStrip => (nv-2) / 3, p::LineListAdjacency => nv / 4, p::LineStripAdjacency => (nv-3), p::TriangleListAdjacency => nv / 6, p::TriangleStripAdjacency => (nv-4) / 2, p::PatchList(num) => nv / (num as u32), } } /// Divides one slice into two at an index. /// /// The first will contain the range in the index-buffer [self.start, mid) (excluding the index mid itself) and the /// second will contain the range [mid, self.end). pub fn split_at(&self, mid: VertexCount) -> (Self, Self) { let mut first = self.clone(); let mut second = self.clone(); first.end = mid; second.start = mid; (first, second) } } /// Type of index-buffer used in a Slice. /// /// The `Auto` variant represents a hypothetical index-buffer from 0 to infinity. In other words, /// all vertices get processed in order. Do note that the `Slice`'s `start` and `end` restrictions /// still apply for this variant. To render every vertex in the `VertexBuffer`, you would set /// `start` to 0, and `end` to the `VertexBuffer`'s length. /// /// The `Index*` variants represent an actual `Buffer` with a list of vertex-indices. The numeric /// suffix specifies the amount of bits to use per index. Each of these also contains a /// base-vertex. This is the index of the first vertex in the `VertexBuffer`. This value will be /// added to every index in the index-buffer, effectively moving the start of the `VertexBuffer` to /// this base-vertex. /// /// # Construction & Handling /// A `IndexBuffer` can be constructed using the `IntoIndexBuffer` trait, from either a slice or a /// `Buffer` of integers, using a device. /// /// An `IndexBuffer` is exclusively used to create `Slice`s. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum IndexBuffer<B: Backend> { /// Represents a hypothetical index-buffer from 0 to infinity. In other words, all vertices /// get processed in order. Auto, /// An index-buffer with unsigned 16 bit indices. Index16(handle::Buffer<B, u16>), /// An index-buffer with unsigned 32 bit indices. Index32(handle::Buffer<B, u32>), } impl<B: Backend> Default for IndexBuffer<B> { fn default() -> Self { IndexBuffer::Auto } } /// A helper trait to create `IndexBuffers` from different kinds of data. pub trait IntoIndexBuffer<B: Backend> { /// Turns self into an `IndexBuffer`. fn into_index_buffer<F: Device<B> +?Sized>(self, device: &mut F) -> IndexBuffer<B>; } impl<B: Backend> IntoIndexBuffer<B> for IndexBuffer<B> { fn into_index_buffer<F: Device<B> +?Sized>(self, _: &mut F) -> IndexBuffer<B> { self } } impl<B: Backend> IntoIndexBuffer<B> for () { fn into_index_buffer<F: Device<B> +?Sized>(self, _: &mut F) -> IndexBuffer<B> { IndexBuffer::Auto } } macro_rules! impl_index_buffer { ($prim_ty:ty, $buf_ty:ident) => ( impl<B: Backend> IntoIndexBuffer<B> for handle::Buffer<B, $prim_ty> { fn into_index_buffer<F: Device<B> +?Sized>(self, _: &mut F) -> IndexBuffer<B> { IndexBuffer::$buf_ty(self) } } impl<'s, B: Backend> IntoIndexBuffer<B> for &'s [$prim_ty] { fn into_index_buffer<F: Device<B> +?Sized>(self, device: &mut F) -> IndexBuffer<B> { device.create_buffer_immutable(self, buffer::Role::Index, Bind::empty()) .unwrap() .into_index_buffer(device) } } ) } impl_index_buffer!(u16, Index16); impl_index_buffer!(u32, Index32);
/// A `Slice` dictates in which and in what order vertices get processed. It is required for /// processing a PSO. ///
random_line_split
slice.rs
//! Slices //! //! See `Slice`-structure documentation for more information on this module. use hal::{handle, buffer}; use hal::{Primitive, Backend, VertexCount}; use hal::command::InstanceParams; use hal::device::Device; use hal::memory::Bind; use format::Format; use pso; /// A `Slice` dictates in which and in what order vertices get processed. It is required for /// processing a PSO. /// /// # Overview /// A `Slice` in gfx has a different meaning from the term slice as employed more broadly in rust (`&[T]`). /// /// A `Slice` object in essence dictates in what order the vertices in a `VertexBuffer` get /// processed. To do this, it contains an internal index-buffer. This `Buffer` is a list of /// indices into this `VertexBuffer` (vertex-index). A vertex-index of 0 represents the first /// vertex in the `VertexBuffer`, a vertex-index of 1 represents the second, 2 represents the /// third, and so on. The vertex-indices in the index-buffer are read in order; every vertex-index /// tells the pipeline which vertex to process next. /// /// Because the same index can re-appear multiple times, duplicate-vertices can be avoided. For /// instance, if you want to draw a square, you need two triangles, and thus six vertices. Because /// the same index can reappear multiple times, this means we can instead use 4 vertices, and 6 /// vertex-indices. /// /// This index-buffer has a few variants. See the `IndexBuffer` documentation for a detailed /// description. /// /// The `start` and `end` fields say where in the index-buffer to start and stop reading. /// Setting `start` to 0, and `end` to the length of the index-buffer, will cause the entire /// index-buffer to be processed. The `base_vertex` dictates the index of the first vertex /// in the `VertexBuffer`. This essentially moves the the start of the `VertexBuffer`, to the /// vertex with this index. /// /// # Construction & Handling /// The `Slice` structure can be constructed automatically when using a `Device` to create a /// vertex buffer. If needed, it can also be created manually. /// /// A `Slice` is required to process a PSO, as it contains the needed information on in what order /// to draw which vertices. As such, every `draw` call on an `Encoder` requires a `Slice`. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Slice<B: Backend> { /// The start index of the index-buffer. Processing will start at this location in the /// index-buffer. pub start: VertexCount, /// The end index in the index-buffer. Processing will stop at this location (exclusive) in /// the index buffer. pub end: VertexCount, /// This is the index of the first vertex in the `VertexBuffer`. This value will be added to /// every index in the index-buffer, effectively moving the start of the `VertexBuffer` to this /// base-vertex. pub base_vertex: VertexCount, /// Instancing configuration. pub instances: Option<InstanceParams>, /// Represents the type of index-buffer used. pub buffer: IndexBuffer<B>, } impl<B: Backend> Slice<B> { /// Creates a new `Slice` to match the supplied vertex buffer, from start to end, in order. pub fn new_match_vertex_buffer<V>(vbuf: &handle::Buffer<B, V>) -> Self where V: pso::buffer::Structure<Format> { Slice { start: 0, end: vbuf.len() as u32, base_vertex: 0, instances: None, buffer: IndexBuffer::Auto, } } /// Calculates the number of primitives of the specified type in this `Slice`. pub fn get_prim_count(&self, prim: Primitive) -> u32 { use hal::Primitive as p; let nv = (self.end - self.start) as u32; match prim { p::PointList => nv, p::LineList => nv / 2, p::LineStrip => (nv-1), p::TriangleList => nv / 3, p::TriangleStrip => (nv-2) / 3, p::LineListAdjacency => nv / 4, p::LineStripAdjacency => (nv-3), p::TriangleListAdjacency => nv / 6, p::TriangleStripAdjacency => (nv-4) / 2, p::PatchList(num) => nv / (num as u32), } } /// Divides one slice into two at an index. /// /// The first will contain the range in the index-buffer [self.start, mid) (excluding the index mid itself) and the /// second will contain the range [mid, self.end). pub fn split_at(&self, mid: VertexCount) -> (Self, Self) { let mut first = self.clone(); let mut second = self.clone(); first.end = mid; second.start = mid; (first, second) } } /// Type of index-buffer used in a Slice. /// /// The `Auto` variant represents a hypothetical index-buffer from 0 to infinity. In other words, /// all vertices get processed in order. Do note that the `Slice`'s `start` and `end` restrictions /// still apply for this variant. To render every vertex in the `VertexBuffer`, you would set /// `start` to 0, and `end` to the `VertexBuffer`'s length. /// /// The `Index*` variants represent an actual `Buffer` with a list of vertex-indices. The numeric /// suffix specifies the amount of bits to use per index. Each of these also contains a /// base-vertex. This is the index of the first vertex in the `VertexBuffer`. This value will be /// added to every index in the index-buffer, effectively moving the start of the `VertexBuffer` to /// this base-vertex. /// /// # Construction & Handling /// A `IndexBuffer` can be constructed using the `IntoIndexBuffer` trait, from either a slice or a /// `Buffer` of integers, using a device. /// /// An `IndexBuffer` is exclusively used to create `Slice`s. #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub enum IndexBuffer<B: Backend> { /// Represents a hypothetical index-buffer from 0 to infinity. In other words, all vertices /// get processed in order. Auto, /// An index-buffer with unsigned 16 bit indices. Index16(handle::Buffer<B, u16>), /// An index-buffer with unsigned 32 bit indices. Index32(handle::Buffer<B, u32>), } impl<B: Backend> Default for IndexBuffer<B> { fn default() -> Self { IndexBuffer::Auto } } /// A helper trait to create `IndexBuffers` from different kinds of data. pub trait IntoIndexBuffer<B: Backend> { /// Turns self into an `IndexBuffer`. fn into_index_buffer<F: Device<B> +?Sized>(self, device: &mut F) -> IndexBuffer<B>; } impl<B: Backend> IntoIndexBuffer<B> for IndexBuffer<B> { fn
<F: Device<B> +?Sized>(self, _: &mut F) -> IndexBuffer<B> { self } } impl<B: Backend> IntoIndexBuffer<B> for () { fn into_index_buffer<F: Device<B> +?Sized>(self, _: &mut F) -> IndexBuffer<B> { IndexBuffer::Auto } } macro_rules! impl_index_buffer { ($prim_ty:ty, $buf_ty:ident) => ( impl<B: Backend> IntoIndexBuffer<B> for handle::Buffer<B, $prim_ty> { fn into_index_buffer<F: Device<B> +?Sized>(self, _: &mut F) -> IndexBuffer<B> { IndexBuffer::$buf_ty(self) } } impl<'s, B: Backend> IntoIndexBuffer<B> for &'s [$prim_ty] { fn into_index_buffer<F: Device<B> +?Sized>(self, device: &mut F) -> IndexBuffer<B> { device.create_buffer_immutable(self, buffer::Role::Index, Bind::empty()) .unwrap() .into_index_buffer(device) } } ) } impl_index_buffer!(u16, Index16); impl_index_buffer!(u32, Index32);
into_index_buffer
identifier_name
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::mem; use std::net::{self, Ipv6Addr, SocketAddr, SocketAddrV6}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::RawFd; use libc::c_char; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr = InetAddr::from_std(&actual); match addr { InetAddr::V4(addr) => { let ip: u32 = 0x7f000001; let port: u16 = 3000; assert_eq!(addr.sin_addr.s_addr, ip.to_be()); assert_eq!(addr.sin_port, port.to_be()); } _ => panic!("nope"), } assert_eq!(addr.to_str(), "127.0.0.1:3000"); let inet = addr.to_std(); assert_eq!(actual, inet); } #[test] pub fn test_inetv6_addr_to_sock_addr() { let port: u16 = 3000; let flowinfo: u32 = 1; let scope_id: u32 = 2; let ip: Ipv6Addr = "fe80::1".parse().unwrap(); let actual = SocketAddr::V6(SocketAddrV6::new(ip, port, flowinfo, scope_id)); let addr = InetAddr::from_std(&actual); match addr { InetAddr::V6(addr) => { assert_eq!(addr.sin6_port, port.to_be()); assert_eq!(addr.sin6_flowinfo, flowinfo); assert_eq!(addr.sin6_scope_id, scope_id); } _ => panic!("nope"), } assert_eq!(actual, addr.to_std()); } #[test] pub fn test_path_to_sock_addr() { let actual = Path::new("/foo/bar"); let addr = UnixAddr::new(actual).unwrap(); let expect: &'static [c_char] = unsafe { mem::transmute(&b"/foo/bar"[..]) }; assert_eq!(&addr.0.sun_path[..8], expect); assert_eq!(addr.path(), Some(actual)); } #[test] pub fn test_getsockname() { use nix::sys::socket::{socket, AddressFamily, SockType, SockFlag}; use nix::sys::socket::{bind, SockAddr}; use tempdir::TempDir; let tempdir = TempDir::new("test_getsockname").unwrap(); let sockname = tempdir.path().join("sock"); let sock = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(sock, &sockaddr).expect("bind failed"); assert_eq!(sockaddr.to_str(), getsockname(sock).expect("getsockname failed").to_str()); } #[test] pub fn test_socketpair() { use nix::unistd::{read, write}; use nix::sys::socket::{socketpair, AddressFamily, SockType, SockFlag}; let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, 0, SockFlag::empty()) .unwrap(); write(fd1, b"hello").unwrap(); let mut buf = [0;5]; read(fd2, &mut buf).unwrap(); assert_eq!(&buf[..], b"hello"); } #[test] pub fn test_scm_rights() { use nix::sys::uio::IoVec; use nix::unistd::{pipe, read, write, close}; use nix::sys::socket::{socketpair, sendmsg, recvmsg, AddressFamily, SockType, SockFlag, ControlMessage, CmsgSpace, MsgFlags, MSG_TRUNC, MSG_CTRUNC}; let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, 0, SockFlag::empty()) .unwrap(); let (r, w) = pipe().unwrap(); let mut received_r: Option<RawFd> = None; { let iov = [IoVec::from_slice(b"hello")]; let fds = [r]; let cmsg = ControlMessage::ScmRights(&fds); assert_eq!(sendmsg(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), 5); close(r).unwrap(); close(fd1).unwrap(); } { let mut buf = [0u8; 5]; let iov = [IoVec::from_mut_slice(&mut buf[..])]; let mut cmsgspace: CmsgSpace<[RawFd; 1]> = CmsgSpace::new(); let msg = recvmsg(fd2, &iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); for cmsg in msg.cmsgs() { if let ControlMessage::ScmRights(fd) = cmsg { assert_eq!(received_r, None); assert_eq!(fd.len(), 1); received_r = Some(fd[0]); } else { panic!("unexpected cmsg"); } } assert_eq!(msg.flags & (MSG_TRUNC | MSG_CTRUNC), MsgFlags::empty()); close(fd2).unwrap(); } let received_r = received_r.expect("Did not receive passed fd"); // Ensure that the received file descriptor works write(w, b"world").unwrap(); let mut buf = [0u8; 5]; read(received_r, &mut buf).unwrap(); assert_eq!(&buf[..], b"world"); close(received_r).unwrap(); close(w).unwrap(); } // Test creating and using named unix domain sockets #[test] pub fn test_unixdomain() { use nix::sys::socket::{AddressFamily, SockType, SockFlag}; use nix::sys::socket::{bind, socket, connect, listen, accept, SockAddr}; use nix::unistd::{read, write, close}; use std::thread; use tempdir::TempDir; let tempdir = TempDir::new("test_unixdomain").unwrap(); let sockname = tempdir.path().join("sock"); let s1 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(s1, &sockaddr).expect("bind failed"); listen(s1, 10).expect("listen failed"); let thr = thread::spawn(move || { let s2 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); connect(s2, &sockaddr).expect("connect failed"); write(s2, b"hello").expect("write failed"); close(s2).unwrap(); }); let s3 = accept(s1).expect("accept failed"); let mut buf = [0;5]; read(s3, &mut buf).unwrap(); close(s3).unwrap(); close(s1).unwrap(); thr.join().unwrap(); assert_eq!(&buf[..], b"hello"); } // Test creating and using named system control sockets #[cfg(any(target_os = "macos", target_os = "ios"))] #[test] pub fn test_syscontrol()
{ use nix::{Errno, Error}; use nix::sys::socket::{AddressFamily, SockType, SockFlag}; use nix::sys::socket::{socket, SockAddr}; use nix::sys::socket::SYSPROTO_CONTROL; let fd = socket(AddressFamily::System, SockType::Datagram, SockFlag::empty(), SYSPROTO_CONTROL).expect("socket failed"); let _sockaddr = SockAddr::new_sys_control(fd, "com.apple.net.utun_control", 0).expect("resolving sys_control name failed"); assert_eq!(SockAddr::new_sys_control(fd, "foo.bar.lol", 0).err(), Some(Error::Sys(Errno::ENOENT))); // requires root privileges // connect(fd, &sockaddr).expect("connect failed"); }
identifier_body
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::mem; use std::net::{self, Ipv6Addr, SocketAddr, SocketAddrV6}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::RawFd; use libc::c_char; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr = InetAddr::from_std(&actual); match addr { InetAddr::V4(addr) => { let ip: u32 = 0x7f000001; let port: u16 = 3000; assert_eq!(addr.sin_addr.s_addr, ip.to_be()); assert_eq!(addr.sin_port, port.to_be()); } _ => panic!("nope"), } assert_eq!(addr.to_str(), "127.0.0.1:3000"); let inet = addr.to_std(); assert_eq!(actual, inet); } #[test] pub fn test_inetv6_addr_to_sock_addr() { let port: u16 = 3000; let flowinfo: u32 = 1; let scope_id: u32 = 2; let ip: Ipv6Addr = "fe80::1".parse().unwrap(); let actual = SocketAddr::V6(SocketAddrV6::new(ip, port, flowinfo, scope_id)); let addr = InetAddr::from_std(&actual); match addr { InetAddr::V6(addr) => { assert_eq!(addr.sin6_port, port.to_be()); assert_eq!(addr.sin6_flowinfo, flowinfo); assert_eq!(addr.sin6_scope_id, scope_id); } _ => panic!("nope"), } assert_eq!(actual, addr.to_std()); } #[test] pub fn test_path_to_sock_addr() { let actual = Path::new("/foo/bar"); let addr = UnixAddr::new(actual).unwrap(); let expect: &'static [c_char] = unsafe { mem::transmute(&b"/foo/bar"[..]) }; assert_eq!(&addr.0.sun_path[..8], expect); assert_eq!(addr.path(), Some(actual)); } #[test] pub fn test_getsockname() { use nix::sys::socket::{socket, AddressFamily, SockType, SockFlag}; use nix::sys::socket::{bind, SockAddr}; use tempdir::TempDir; let tempdir = TempDir::new("test_getsockname").unwrap(); let sockname = tempdir.path().join("sock"); let sock = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(sock, &sockaddr).expect("bind failed"); assert_eq!(sockaddr.to_str(), getsockname(sock).expect("getsockname failed").to_str()); } #[test] pub fn test_socketpair() { use nix::unistd::{read, write}; use nix::sys::socket::{socketpair, AddressFamily, SockType, SockFlag}; let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, 0, SockFlag::empty()) .unwrap(); write(fd1, b"hello").unwrap(); let mut buf = [0;5]; read(fd2, &mut buf).unwrap(); assert_eq!(&buf[..], b"hello"); } #[test] pub fn test_scm_rights() { use nix::sys::uio::IoVec; use nix::unistd::{pipe, read, write, close}; use nix::sys::socket::{socketpair, sendmsg, recvmsg, AddressFamily, SockType, SockFlag, ControlMessage, CmsgSpace, MsgFlags, MSG_TRUNC, MSG_CTRUNC}; let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, 0, SockFlag::empty()) .unwrap(); let (r, w) = pipe().unwrap(); let mut received_r: Option<RawFd> = None; { let iov = [IoVec::from_slice(b"hello")]; let fds = [r]; let cmsg = ControlMessage::ScmRights(&fds); assert_eq!(sendmsg(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), 5); close(r).unwrap(); close(fd1).unwrap(); } { let mut buf = [0u8; 5]; let iov = [IoVec::from_mut_slice(&mut buf[..])]; let mut cmsgspace: CmsgSpace<[RawFd; 1]> = CmsgSpace::new(); let msg = recvmsg(fd2, &iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); for cmsg in msg.cmsgs() { if let ControlMessage::ScmRights(fd) = cmsg { assert_eq!(received_r, None); assert_eq!(fd.len(), 1); received_r = Some(fd[0]); } else { panic!("unexpected cmsg"); } } assert_eq!(msg.flags & (MSG_TRUNC | MSG_CTRUNC), MsgFlags::empty()); close(fd2).unwrap(); } let received_r = received_r.expect("Did not receive passed fd"); // Ensure that the received file descriptor works write(w, b"world").unwrap(); let mut buf = [0u8; 5]; read(received_r, &mut buf).unwrap(); assert_eq!(&buf[..], b"world"); close(received_r).unwrap(); close(w).unwrap(); } // Test creating and using named unix domain sockets #[test] pub fn
() { use nix::sys::socket::{AddressFamily, SockType, SockFlag}; use nix::sys::socket::{bind, socket, connect, listen, accept, SockAddr}; use nix::unistd::{read, write, close}; use std::thread; use tempdir::TempDir; let tempdir = TempDir::new("test_unixdomain").unwrap(); let sockname = tempdir.path().join("sock"); let s1 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(s1, &sockaddr).expect("bind failed"); listen(s1, 10).expect("listen failed"); let thr = thread::spawn(move || { let s2 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); connect(s2, &sockaddr).expect("connect failed"); write(s2, b"hello").expect("write failed"); close(s2).unwrap(); }); let s3 = accept(s1).expect("accept failed"); let mut buf = [0;5]; read(s3, &mut buf).unwrap(); close(s3).unwrap(); close(s1).unwrap(); thr.join().unwrap(); assert_eq!(&buf[..], b"hello"); } // Test creating and using named system control sockets #[cfg(any(target_os = "macos", target_os = "ios"))] #[test] pub fn test_syscontrol() { use nix::{Errno, Error}; use nix::sys::socket::{AddressFamily, SockType, SockFlag}; use nix::sys::socket::{socket, SockAddr}; use nix::sys::socket::SYSPROTO_CONTROL; let fd = socket(AddressFamily::System, SockType::Datagram, SockFlag::empty(), SYSPROTO_CONTROL).expect("socket failed"); let _sockaddr = SockAddr::new_sys_control(fd, "com.apple.net.utun_control", 0).expect("resolving sys_control name failed"); assert_eq!(SockAddr::new_sys_control(fd, "foo.bar.lol", 0).err(), Some(Error::Sys(Errno::ENOENT))); // requires root privileges // connect(fd, &sockaddr).expect("connect failed"); }
test_unixdomain
identifier_name
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::mem; use std::net::{self, Ipv6Addr, SocketAddr, SocketAddrV6}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::RawFd; use libc::c_char; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr = InetAddr::from_std(&actual); match addr { InetAddr::V4(addr) => { let ip: u32 = 0x7f000001; let port: u16 = 3000; assert_eq!(addr.sin_addr.s_addr, ip.to_be()); assert_eq!(addr.sin_port, port.to_be()); } _ => panic!("nope"), } assert_eq!(addr.to_str(), "127.0.0.1:3000"); let inet = addr.to_std(); assert_eq!(actual, inet); } #[test] pub fn test_inetv6_addr_to_sock_addr() { let port: u16 = 3000; let flowinfo: u32 = 1; let scope_id: u32 = 2; let ip: Ipv6Addr = "fe80::1".parse().unwrap(); let actual = SocketAddr::V6(SocketAddrV6::new(ip, port, flowinfo, scope_id)); let addr = InetAddr::from_std(&actual); match addr { InetAddr::V6(addr) => { assert_eq!(addr.sin6_port, port.to_be()); assert_eq!(addr.sin6_flowinfo, flowinfo); assert_eq!(addr.sin6_scope_id, scope_id); } _ => panic!("nope"), } assert_eq!(actual, addr.to_std()); } #[test] pub fn test_path_to_sock_addr() { let actual = Path::new("/foo/bar"); let addr = UnixAddr::new(actual).unwrap(); let expect: &'static [c_char] = unsafe { mem::transmute(&b"/foo/bar"[..]) }; assert_eq!(&addr.0.sun_path[..8], expect); assert_eq!(addr.path(), Some(actual)); } #[test] pub fn test_getsockname() { use nix::sys::socket::{socket, AddressFamily, SockType, SockFlag}; use nix::sys::socket::{bind, SockAddr}; use tempdir::TempDir; let tempdir = TempDir::new("test_getsockname").unwrap(); let sockname = tempdir.path().join("sock"); let sock = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(sock, &sockaddr).expect("bind failed"); assert_eq!(sockaddr.to_str(), getsockname(sock).expect("getsockname failed").to_str()); } #[test] pub fn test_socketpair() { use nix::unistd::{read, write}; use nix::sys::socket::{socketpair, AddressFamily, SockType, SockFlag}; let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, 0, SockFlag::empty()) .unwrap(); write(fd1, b"hello").unwrap(); let mut buf = [0;5]; read(fd2, &mut buf).unwrap(); assert_eq!(&buf[..], b"hello"); } #[test] pub fn test_scm_rights() { use nix::sys::uio::IoVec; use nix::unistd::{pipe, read, write, close}; use nix::sys::socket::{socketpair, sendmsg, recvmsg, AddressFamily, SockType, SockFlag, ControlMessage, CmsgSpace, MsgFlags, MSG_TRUNC, MSG_CTRUNC}; let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, 0, SockFlag::empty()) .unwrap(); let (r, w) = pipe().unwrap(); let mut received_r: Option<RawFd> = None; { let iov = [IoVec::from_slice(b"hello")]; let fds = [r]; let cmsg = ControlMessage::ScmRights(&fds); assert_eq!(sendmsg(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), 5); close(r).unwrap(); close(fd1).unwrap(); } { let mut buf = [0u8; 5]; let iov = [IoVec::from_mut_slice(&mut buf[..])]; let mut cmsgspace: CmsgSpace<[RawFd; 1]> = CmsgSpace::new(); let msg = recvmsg(fd2, &iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); for cmsg in msg.cmsgs() { if let ControlMessage::ScmRights(fd) = cmsg { assert_eq!(received_r, None); assert_eq!(fd.len(), 1); received_r = Some(fd[0]); } else
} assert_eq!(msg.flags & (MSG_TRUNC | MSG_CTRUNC), MsgFlags::empty()); close(fd2).unwrap(); } let received_r = received_r.expect("Did not receive passed fd"); // Ensure that the received file descriptor works write(w, b"world").unwrap(); let mut buf = [0u8; 5]; read(received_r, &mut buf).unwrap(); assert_eq!(&buf[..], b"world"); close(received_r).unwrap(); close(w).unwrap(); } // Test creating and using named unix domain sockets #[test] pub fn test_unixdomain() { use nix::sys::socket::{AddressFamily, SockType, SockFlag}; use nix::sys::socket::{bind, socket, connect, listen, accept, SockAddr}; use nix::unistd::{read, write, close}; use std::thread; use tempdir::TempDir; let tempdir = TempDir::new("test_unixdomain").unwrap(); let sockname = tempdir.path().join("sock"); let s1 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(s1, &sockaddr).expect("bind failed"); listen(s1, 10).expect("listen failed"); let thr = thread::spawn(move || { let s2 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); connect(s2, &sockaddr).expect("connect failed"); write(s2, b"hello").expect("write failed"); close(s2).unwrap(); }); let s3 = accept(s1).expect("accept failed"); let mut buf = [0;5]; read(s3, &mut buf).unwrap(); close(s3).unwrap(); close(s1).unwrap(); thr.join().unwrap(); assert_eq!(&buf[..], b"hello"); } // Test creating and using named system control sockets #[cfg(any(target_os = "macos", target_os = "ios"))] #[test] pub fn test_syscontrol() { use nix::{Errno, Error}; use nix::sys::socket::{AddressFamily, SockType, SockFlag}; use nix::sys::socket::{socket, SockAddr}; use nix::sys::socket::SYSPROTO_CONTROL; let fd = socket(AddressFamily::System, SockType::Datagram, SockFlag::empty(), SYSPROTO_CONTROL).expect("socket failed"); let _sockaddr = SockAddr::new_sys_control(fd, "com.apple.net.utun_control", 0).expect("resolving sys_control name failed"); assert_eq!(SockAddr::new_sys_control(fd, "foo.bar.lol", 0).err(), Some(Error::Sys(Errno::ENOENT))); // requires root privileges // connect(fd, &sockaddr).expect("connect failed"); }
{ panic!("unexpected cmsg"); }
conditional_block
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::mem; use std::net::{self, Ipv6Addr, SocketAddr, SocketAddrV6}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::RawFd; use libc::c_char; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); let addr = InetAddr::from_std(&actual); match addr { InetAddr::V4(addr) => { let ip: u32 = 0x7f000001; let port: u16 = 3000; assert_eq!(addr.sin_addr.s_addr, ip.to_be()); assert_eq!(addr.sin_port, port.to_be()); } _ => panic!("nope"), } assert_eq!(addr.to_str(), "127.0.0.1:3000"); let inet = addr.to_std(); assert_eq!(actual, inet); } #[test] pub fn test_inetv6_addr_to_sock_addr() {
let flowinfo: u32 = 1; let scope_id: u32 = 2; let ip: Ipv6Addr = "fe80::1".parse().unwrap(); let actual = SocketAddr::V6(SocketAddrV6::new(ip, port, flowinfo, scope_id)); let addr = InetAddr::from_std(&actual); match addr { InetAddr::V6(addr) => { assert_eq!(addr.sin6_port, port.to_be()); assert_eq!(addr.sin6_flowinfo, flowinfo); assert_eq!(addr.sin6_scope_id, scope_id); } _ => panic!("nope"), } assert_eq!(actual, addr.to_std()); } #[test] pub fn test_path_to_sock_addr() { let actual = Path::new("/foo/bar"); let addr = UnixAddr::new(actual).unwrap(); let expect: &'static [c_char] = unsafe { mem::transmute(&b"/foo/bar"[..]) }; assert_eq!(&addr.0.sun_path[..8], expect); assert_eq!(addr.path(), Some(actual)); } #[test] pub fn test_getsockname() { use nix::sys::socket::{socket, AddressFamily, SockType, SockFlag}; use nix::sys::socket::{bind, SockAddr}; use tempdir::TempDir; let tempdir = TempDir::new("test_getsockname").unwrap(); let sockname = tempdir.path().join("sock"); let sock = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(sock, &sockaddr).expect("bind failed"); assert_eq!(sockaddr.to_str(), getsockname(sock).expect("getsockname failed").to_str()); } #[test] pub fn test_socketpair() { use nix::unistd::{read, write}; use nix::sys::socket::{socketpair, AddressFamily, SockType, SockFlag}; let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, 0, SockFlag::empty()) .unwrap(); write(fd1, b"hello").unwrap(); let mut buf = [0;5]; read(fd2, &mut buf).unwrap(); assert_eq!(&buf[..], b"hello"); } #[test] pub fn test_scm_rights() { use nix::sys::uio::IoVec; use nix::unistd::{pipe, read, write, close}; use nix::sys::socket::{socketpair, sendmsg, recvmsg, AddressFamily, SockType, SockFlag, ControlMessage, CmsgSpace, MsgFlags, MSG_TRUNC, MSG_CTRUNC}; let (fd1, fd2) = socketpair(AddressFamily::Unix, SockType::Stream, 0, SockFlag::empty()) .unwrap(); let (r, w) = pipe().unwrap(); let mut received_r: Option<RawFd> = None; { let iov = [IoVec::from_slice(b"hello")]; let fds = [r]; let cmsg = ControlMessage::ScmRights(&fds); assert_eq!(sendmsg(fd1, &iov, &[cmsg], MsgFlags::empty(), None).unwrap(), 5); close(r).unwrap(); close(fd1).unwrap(); } { let mut buf = [0u8; 5]; let iov = [IoVec::from_mut_slice(&mut buf[..])]; let mut cmsgspace: CmsgSpace<[RawFd; 1]> = CmsgSpace::new(); let msg = recvmsg(fd2, &iov, Some(&mut cmsgspace), MsgFlags::empty()).unwrap(); for cmsg in msg.cmsgs() { if let ControlMessage::ScmRights(fd) = cmsg { assert_eq!(received_r, None); assert_eq!(fd.len(), 1); received_r = Some(fd[0]); } else { panic!("unexpected cmsg"); } } assert_eq!(msg.flags & (MSG_TRUNC | MSG_CTRUNC), MsgFlags::empty()); close(fd2).unwrap(); } let received_r = received_r.expect("Did not receive passed fd"); // Ensure that the received file descriptor works write(w, b"world").unwrap(); let mut buf = [0u8; 5]; read(received_r, &mut buf).unwrap(); assert_eq!(&buf[..], b"world"); close(received_r).unwrap(); close(w).unwrap(); } // Test creating and using named unix domain sockets #[test] pub fn test_unixdomain() { use nix::sys::socket::{AddressFamily, SockType, SockFlag}; use nix::sys::socket::{bind, socket, connect, listen, accept, SockAddr}; use nix::unistd::{read, write, close}; use std::thread; use tempdir::TempDir; let tempdir = TempDir::new("test_unixdomain").unwrap(); let sockname = tempdir.path().join("sock"); let s1 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); let sockaddr = SockAddr::new_unix(&sockname).unwrap(); bind(s1, &sockaddr).expect("bind failed"); listen(s1, 10).expect("listen failed"); let thr = thread::spawn(move || { let s2 = socket(AddressFamily::Unix, SockType::Stream, SockFlag::empty(), 0).expect("socket failed"); connect(s2, &sockaddr).expect("connect failed"); write(s2, b"hello").expect("write failed"); close(s2).unwrap(); }); let s3 = accept(s1).expect("accept failed"); let mut buf = [0;5]; read(s3, &mut buf).unwrap(); close(s3).unwrap(); close(s1).unwrap(); thr.join().unwrap(); assert_eq!(&buf[..], b"hello"); } // Test creating and using named system control sockets #[cfg(any(target_os = "macos", target_os = "ios"))] #[test] pub fn test_syscontrol() { use nix::{Errno, Error}; use nix::sys::socket::{AddressFamily, SockType, SockFlag}; use nix::sys::socket::{socket, SockAddr}; use nix::sys::socket::SYSPROTO_CONTROL; let fd = socket(AddressFamily::System, SockType::Datagram, SockFlag::empty(), SYSPROTO_CONTROL).expect("socket failed"); let _sockaddr = SockAddr::new_sys_control(fd, "com.apple.net.utun_control", 0).expect("resolving sys_control name failed"); assert_eq!(SockAddr::new_sys_control(fd, "foo.bar.lol", 0).err(), Some(Error::Sys(Errno::ENOENT))); // requires root privileges // connect(fd, &sockaddr).expect("connect failed"); }
let port: u16 = 3000;
random_line_split
htmltabledatacellelement.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::HTMLTableDataCellElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTableDataCellElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLTableDataCellElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmltablecellelement::HTMLTableCellElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLTableDataCellElement { pub htmltablecellelement: HTMLTableCellElement, } impl HTMLTableDataCellElementDerived for EventTarget { fn is_htmltabledatacellelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLTableDataCellElementTypeId)) } } impl HTMLTableDataCellElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLTableDataCellElement { HTMLTableDataCellElement { htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableDataCellElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLTableDataCellElement> { let element = HTMLTableDataCellElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLTableDataCellElementBinding::Wrap) } } pub trait HTMLTableDataCellElementMethods { } impl Reflectable for HTMLTableDataCellElement { fn
<'a>(&'a self) -> &'a Reflector { self.htmltablecellelement.reflector() } }
reflector
identifier_name
htmltabledatacellelement.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::HTMLTableDataCellElementBinding; use dom::bindings::codegen::InheritTypes::HTMLTableDataCellElementDerived; use dom::bindings::js::{JSRef, Temporary}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::Document; use dom::element::HTMLTableDataCellElementTypeId; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmltablecellelement::HTMLTableCellElement; use dom::node::{Node, ElementNodeTypeId}; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLTableDataCellElement { pub htmltablecellelement: HTMLTableCellElement, } impl HTMLTableDataCellElementDerived for EventTarget {
self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLTableDataCellElementTypeId)) } } impl HTMLTableDataCellElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLTableDataCellElement { HTMLTableDataCellElement { htmltablecellelement: HTMLTableCellElement::new_inherited(HTMLTableDataCellElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLTableDataCellElement> { let element = HTMLTableDataCellElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLTableDataCellElementBinding::Wrap) } } pub trait HTMLTableDataCellElementMethods { } impl Reflectable for HTMLTableDataCellElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmltablecellelement.reflector() } }
fn is_htmltabledatacellelement(&self) -> bool {
random_line_split
main.rs
extern crate scoped_pool; #[macro_use] extern crate log; extern crate ansi_term; extern crate env_logger; extern crate pbr; extern crate serde_derive; extern crate term_painter; #[macro_use] extern crate clap; extern crate anyhow; extern crate glob; extern crate num_cpus; extern crate regex; extern crate toml; extern crate unic_char_range; extern crate walkdir; use args::Args; mod app; mod args; mod check; mod clean; mod config; mod search; use pbr::ProgressBar; use std::{ fs::File, io::prelude::*, num, process, sync::{ mpsc::{sync_channel, SyncSender}, Arc, }, thread, }; macro_rules! eprintln { ($($tt:tt)*) => {{ use std::io::Write; let _ = writeln!(&mut ::std::io::stderr(), $($tt)*); }} } #[allow(dead_code)] fn main() { match Args::parse().map(Arc::new).and_then(run) { Ok(0) => process::exit(0), Ok(_) => process::exit(1), Err(err) => { eprintln!("{}", err); process::exit(1); } } } fn run(args: Arc<Args>) -> Result<u64, num::ParseIntError> { let enforcer_cfg = config::get_cfg(args.config_file()); if args.status() { println!(" using this config: {:?}", enforcer_cfg); std::process::exit(0); } let cfg_ignores: &Vec<String> = &enforcer_cfg.ignore; let cfg_endings = enforcer_cfg.endings; let file_endings = if!args.endings().is_empty() { args.endings() } else { &cfg_endings }; let mut checked_files: u32 = 0; let mut had_tabs: u32 = 0; let mut had_trailing_ws: u32 = 0; let mut had_illegals: u32 = 0; let mut had_too_long_lines: u32 = 0; let mut had_win_line_endings: u32 = 0; let clean_f = args.clean(); let tabs_f = args.tabs(); let use_crlf = args.use_crlf(); let thread_count = args.threads(); let color_f = args.color(); let max_line_length = args.line_length(); let start_dir = args.path(); debug!("args:{:?}", args); if args.quiet() { println!("quiet flag was used but is deprecated...use verbosity instead"); } let info_level: check::InfoLevel = args.info_level(); let paths = search::find_matches(start_dir.as_path(), cfg_ignores, file_endings); let count: u64 = paths.len() as u64; let mut pb = ProgressBar::new(count); // logger thread let (logging_tx, logging_rx) = sync_channel::<Option<String>>(0); let stop_logging_tx = logging_tx.clone(); thread::spawn(move || { let mut done = false; while!done { done = logging_rx .recv() .ok() // not done when we got a receive error (sender end of connection closed) .map_or(false, |maybe_print| { maybe_print // a None indicates that logging is done .map_or(true, |p| // just print the string we received {print!("{}", p); false}) }); } }); let (w_chan, r_chan) = sync_channel(thread_count); thread::spawn(move || { use scoped_pool::Pool; let pool = Pool::new(thread_count); pool.scoped(|scope| { for path in paths { let ch: SyncSender<Result<u8, std::io::Error>> = w_chan.clone(); let l_ch: SyncSender<Option<String>> = logging_tx.clone(); scope.execute(move || { if!check::is_dir(path.as_path()) { let p = path.clone(); let mut f = File::open(path) .unwrap_or_else(|_| panic!("error reading file {:?}", p)); let mut buffer = Vec::new(); f.read_to_end(&mut buffer) .unwrap_or_else(|_| panic!("error reading file {:?}", p)); let r = check::check_path( p.as_path(), &buffer, clean_f, info_level, max_line_length, if tabs_f { clean::TabStrategy::Tabify } else { clean::TabStrategy::Untabify }, if use_crlf { clean::LineEnding::CRLF } else { clean::LineEnding::LF }, l_ch, ); ch.send(r).expect("send result with SyncSender"); } }); } }); }); for _ in 0..count { match r_chan.recv() { Ok(res) => match res { Ok(r) => { if (r & check::HAS_TABS) > 0 { had_tabs += 1 } if (r & check::TRAILING_SPACES) > 0 { had_trailing_ws += 1 } if (r & check::HAS_ILLEGAL_CHARACTERS) > 0 { had_illegals += 1 } if (r & check::LINE_TOO_LONG) > 0 { had_too_long_lines += 1 } if (r & check::HAS_WINDOWS_LINE_ENDINGS) > 0 { had_win_line_endings += 1 } } Err(e) => { error!("error occured here: {}", e); } }, Err(e) => { panic!("error in channel: {}", e); } } checked_files += 1; if info_level == check::InfoLevel::Quiet { pb.inc(); } } if info_level == check::InfoLevel::Quiet { pb.finish(); }; let _ = stop_logging_tx.send(None); let findings = Findings { had_tabs, had_trailing_ws, had_illegals, had_too_long_lines, had_win_line_endings, checked_files, }; report_findings(info_level == check::InfoLevel::Quiet, findings, color_f) } #[derive(Debug)] struct Findings { had_tabs: u32, had_trailing_ws: u32, had_illegals: u32, had_too_long_lines: u32, had_win_line_endings: u32, checked_files: u32, } fn report_findings( quiet: bool, findings: Findings, colored: bool, ) -> Result<u64, num::ParseIntError> { let total_errors = findings.had_tabs + findings.had_illegals + findings.had_trailing_ws + findings.had_too_long_lines + findings.had_win_line_endings; if quiet { if colored { println!("{}: {}", check::bold("enforcer-error-count"), total_errors); } else { println!("enforcer-error-count: {}", total_errors); } } if total_errors > 0 { if colored { println!( "checked {} files {}", findings.checked_files, check::bold("(enforcer_errors!)") ); } else { println!( "checked {} files (enforcer_errors!)", findings.checked_files ); } if findings.had_tabs > 0 { println!(" [with TABS:{}]", findings.had_tabs) } if findings.had_illegals > 0 { println!(" [with ILLEGAL CHARS:{}]", findings.had_illegals) } if findings.had_trailing_ws > 0
if findings.had_too_long_lines > 0 { println!(" [with TOO LONG LINES:{}]", findings.had_too_long_lines) } if findings.had_win_line_endings > 0 { println!( " [with WINDOWS LINE ENDINGS:{}]", findings.had_win_line_endings ) } Ok(1) } else { if colored { println!( "checked {} files {}", findings.checked_files, check::green("(enforcer_clean!)") ); } else { println!("checked {} files (enforcer_clean!)", findings.checked_files); } Ok(0) } }
{ println!(" [with TRAILING SPACES:{}]", findings.had_trailing_ws) }
conditional_block
main.rs
extern crate scoped_pool; #[macro_use] extern crate log; extern crate ansi_term; extern crate env_logger; extern crate pbr;
extern crate anyhow; extern crate glob; extern crate num_cpus; extern crate regex; extern crate toml; extern crate unic_char_range; extern crate walkdir; use args::Args; mod app; mod args; mod check; mod clean; mod config; mod search; use pbr::ProgressBar; use std::{ fs::File, io::prelude::*, num, process, sync::{ mpsc::{sync_channel, SyncSender}, Arc, }, thread, }; macro_rules! eprintln { ($($tt:tt)*) => {{ use std::io::Write; let _ = writeln!(&mut ::std::io::stderr(), $($tt)*); }} } #[allow(dead_code)] fn main() { match Args::parse().map(Arc::new).and_then(run) { Ok(0) => process::exit(0), Ok(_) => process::exit(1), Err(err) => { eprintln!("{}", err); process::exit(1); } } } fn run(args: Arc<Args>) -> Result<u64, num::ParseIntError> { let enforcer_cfg = config::get_cfg(args.config_file()); if args.status() { println!(" using this config: {:?}", enforcer_cfg); std::process::exit(0); } let cfg_ignores: &Vec<String> = &enforcer_cfg.ignore; let cfg_endings = enforcer_cfg.endings; let file_endings = if!args.endings().is_empty() { args.endings() } else { &cfg_endings }; let mut checked_files: u32 = 0; let mut had_tabs: u32 = 0; let mut had_trailing_ws: u32 = 0; let mut had_illegals: u32 = 0; let mut had_too_long_lines: u32 = 0; let mut had_win_line_endings: u32 = 0; let clean_f = args.clean(); let tabs_f = args.tabs(); let use_crlf = args.use_crlf(); let thread_count = args.threads(); let color_f = args.color(); let max_line_length = args.line_length(); let start_dir = args.path(); debug!("args:{:?}", args); if args.quiet() { println!("quiet flag was used but is deprecated...use verbosity instead"); } let info_level: check::InfoLevel = args.info_level(); let paths = search::find_matches(start_dir.as_path(), cfg_ignores, file_endings); let count: u64 = paths.len() as u64; let mut pb = ProgressBar::new(count); // logger thread let (logging_tx, logging_rx) = sync_channel::<Option<String>>(0); let stop_logging_tx = logging_tx.clone(); thread::spawn(move || { let mut done = false; while!done { done = logging_rx .recv() .ok() // not done when we got a receive error (sender end of connection closed) .map_or(false, |maybe_print| { maybe_print // a None indicates that logging is done .map_or(true, |p| // just print the string we received {print!("{}", p); false}) }); } }); let (w_chan, r_chan) = sync_channel(thread_count); thread::spawn(move || { use scoped_pool::Pool; let pool = Pool::new(thread_count); pool.scoped(|scope| { for path in paths { let ch: SyncSender<Result<u8, std::io::Error>> = w_chan.clone(); let l_ch: SyncSender<Option<String>> = logging_tx.clone(); scope.execute(move || { if!check::is_dir(path.as_path()) { let p = path.clone(); let mut f = File::open(path) .unwrap_or_else(|_| panic!("error reading file {:?}", p)); let mut buffer = Vec::new(); f.read_to_end(&mut buffer) .unwrap_or_else(|_| panic!("error reading file {:?}", p)); let r = check::check_path( p.as_path(), &buffer, clean_f, info_level, max_line_length, if tabs_f { clean::TabStrategy::Tabify } else { clean::TabStrategy::Untabify }, if use_crlf { clean::LineEnding::CRLF } else { clean::LineEnding::LF }, l_ch, ); ch.send(r).expect("send result with SyncSender"); } }); } }); }); for _ in 0..count { match r_chan.recv() { Ok(res) => match res { Ok(r) => { if (r & check::HAS_TABS) > 0 { had_tabs += 1 } if (r & check::TRAILING_SPACES) > 0 { had_trailing_ws += 1 } if (r & check::HAS_ILLEGAL_CHARACTERS) > 0 { had_illegals += 1 } if (r & check::LINE_TOO_LONG) > 0 { had_too_long_lines += 1 } if (r & check::HAS_WINDOWS_LINE_ENDINGS) > 0 { had_win_line_endings += 1 } } Err(e) => { error!("error occured here: {}", e); } }, Err(e) => { panic!("error in channel: {}", e); } } checked_files += 1; if info_level == check::InfoLevel::Quiet { pb.inc(); } } if info_level == check::InfoLevel::Quiet { pb.finish(); }; let _ = stop_logging_tx.send(None); let findings = Findings { had_tabs, had_trailing_ws, had_illegals, had_too_long_lines, had_win_line_endings, checked_files, }; report_findings(info_level == check::InfoLevel::Quiet, findings, color_f) } #[derive(Debug)] struct Findings { had_tabs: u32, had_trailing_ws: u32, had_illegals: u32, had_too_long_lines: u32, had_win_line_endings: u32, checked_files: u32, } fn report_findings( quiet: bool, findings: Findings, colored: bool, ) -> Result<u64, num::ParseIntError> { let total_errors = findings.had_tabs + findings.had_illegals + findings.had_trailing_ws + findings.had_too_long_lines + findings.had_win_line_endings; if quiet { if colored { println!("{}: {}", check::bold("enforcer-error-count"), total_errors); } else { println!("enforcer-error-count: {}", total_errors); } } if total_errors > 0 { if colored { println!( "checked {} files {}", findings.checked_files, check::bold("(enforcer_errors!)") ); } else { println!( "checked {} files (enforcer_errors!)", findings.checked_files ); } if findings.had_tabs > 0 { println!(" [with TABS:{}]", findings.had_tabs) } if findings.had_illegals > 0 { println!(" [with ILLEGAL CHARS:{}]", findings.had_illegals) } if findings.had_trailing_ws > 0 { println!(" [with TRAILING SPACES:{}]", findings.had_trailing_ws) } if findings.had_too_long_lines > 0 { println!(" [with TOO LONG LINES:{}]", findings.had_too_long_lines) } if findings.had_win_line_endings > 0 { println!( " [with WINDOWS LINE ENDINGS:{}]", findings.had_win_line_endings ) } Ok(1) } else { if colored { println!( "checked {} files {}", findings.checked_files, check::green("(enforcer_clean!)") ); } else { println!("checked {} files (enforcer_clean!)", findings.checked_files); } Ok(0) } }
extern crate serde_derive; extern crate term_painter; #[macro_use] extern crate clap;
random_line_split
main.rs
extern crate scoped_pool; #[macro_use] extern crate log; extern crate ansi_term; extern crate env_logger; extern crate pbr; extern crate serde_derive; extern crate term_painter; #[macro_use] extern crate clap; extern crate anyhow; extern crate glob; extern crate num_cpus; extern crate regex; extern crate toml; extern crate unic_char_range; extern crate walkdir; use args::Args; mod app; mod args; mod check; mod clean; mod config; mod search; use pbr::ProgressBar; use std::{ fs::File, io::prelude::*, num, process, sync::{ mpsc::{sync_channel, SyncSender}, Arc, }, thread, }; macro_rules! eprintln { ($($tt:tt)*) => {{ use std::io::Write; let _ = writeln!(&mut ::std::io::stderr(), $($tt)*); }} } #[allow(dead_code)] fn main() { match Args::parse().map(Arc::new).and_then(run) { Ok(0) => process::exit(0), Ok(_) => process::exit(1), Err(err) => { eprintln!("{}", err); process::exit(1); } } } fn run(args: Arc<Args>) -> Result<u64, num::ParseIntError>
let clean_f = args.clean(); let tabs_f = args.tabs(); let use_crlf = args.use_crlf(); let thread_count = args.threads(); let color_f = args.color(); let max_line_length = args.line_length(); let start_dir = args.path(); debug!("args:{:?}", args); if args.quiet() { println!("quiet flag was used but is deprecated...use verbosity instead"); } let info_level: check::InfoLevel = args.info_level(); let paths = search::find_matches(start_dir.as_path(), cfg_ignores, file_endings); let count: u64 = paths.len() as u64; let mut pb = ProgressBar::new(count); // logger thread let (logging_tx, logging_rx) = sync_channel::<Option<String>>(0); let stop_logging_tx = logging_tx.clone(); thread::spawn(move || { let mut done = false; while!done { done = logging_rx .recv() .ok() // not done when we got a receive error (sender end of connection closed) .map_or(false, |maybe_print| { maybe_print // a None indicates that logging is done .map_or(true, |p| // just print the string we received {print!("{}", p); false}) }); } }); let (w_chan, r_chan) = sync_channel(thread_count); thread::spawn(move || { use scoped_pool::Pool; let pool = Pool::new(thread_count); pool.scoped(|scope| { for path in paths { let ch: SyncSender<Result<u8, std::io::Error>> = w_chan.clone(); let l_ch: SyncSender<Option<String>> = logging_tx.clone(); scope.execute(move || { if!check::is_dir(path.as_path()) { let p = path.clone(); let mut f = File::open(path) .unwrap_or_else(|_| panic!("error reading file {:?}", p)); let mut buffer = Vec::new(); f.read_to_end(&mut buffer) .unwrap_or_else(|_| panic!("error reading file {:?}", p)); let r = check::check_path( p.as_path(), &buffer, clean_f, info_level, max_line_length, if tabs_f { clean::TabStrategy::Tabify } else { clean::TabStrategy::Untabify }, if use_crlf { clean::LineEnding::CRLF } else { clean::LineEnding::LF }, l_ch, ); ch.send(r).expect("send result with SyncSender"); } }); } }); }); for _ in 0..count { match r_chan.recv() { Ok(res) => match res { Ok(r) => { if (r & check::HAS_TABS) > 0 { had_tabs += 1 } if (r & check::TRAILING_SPACES) > 0 { had_trailing_ws += 1 } if (r & check::HAS_ILLEGAL_CHARACTERS) > 0 { had_illegals += 1 } if (r & check::LINE_TOO_LONG) > 0 { had_too_long_lines += 1 } if (r & check::HAS_WINDOWS_LINE_ENDINGS) > 0 { had_win_line_endings += 1 } } Err(e) => { error!("error occured here: {}", e); } }, Err(e) => { panic!("error in channel: {}", e); } } checked_files += 1; if info_level == check::InfoLevel::Quiet { pb.inc(); } } if info_level == check::InfoLevel::Quiet { pb.finish(); }; let _ = stop_logging_tx.send(None); let findings = Findings { had_tabs, had_trailing_ws, had_illegals, had_too_long_lines, had_win_line_endings, checked_files, }; report_findings(info_level == check::InfoLevel::Quiet, findings, color_f) } #[derive(Debug)] struct Findings { had_tabs: u32, had_trailing_ws: u32, had_illegals: u32, had_too_long_lines: u32, had_win_line_endings: u32, checked_files: u32, } fn report_findings( quiet: bool, findings: Findings, colored: bool, ) -> Result<u64, num::ParseIntError> { let total_errors = findings.had_tabs + findings.had_illegals + findings.had_trailing_ws + findings.had_too_long_lines + findings.had_win_line_endings; if quiet { if colored { println!("{}: {}", check::bold("enforcer-error-count"), total_errors); } else { println!("enforcer-error-count: {}", total_errors); } } if total_errors > 0 { if colored { println!( "checked {} files {}", findings.checked_files, check::bold("(enforcer_errors!)") ); } else { println!( "checked {} files (enforcer_errors!)", findings.checked_files ); } if findings.had_tabs > 0 { println!(" [with TABS:{}]", findings.had_tabs) } if findings.had_illegals > 0 { println!(" [with ILLEGAL CHARS:{}]", findings.had_illegals) } if findings.had_trailing_ws > 0 { println!(" [with TRAILING SPACES:{}]", findings.had_trailing_ws) } if findings.had_too_long_lines > 0 { println!(" [with TOO LONG LINES:{}]", findings.had_too_long_lines) } if findings.had_win_line_endings > 0 { println!( " [with WINDOWS LINE ENDINGS:{}]", findings.had_win_line_endings ) } Ok(1) } else { if colored { println!( "checked {} files {}", findings.checked_files, check::green("(enforcer_clean!)") ); } else { println!("checked {} files (enforcer_clean!)", findings.checked_files); } Ok(0) } }
{ let enforcer_cfg = config::get_cfg(args.config_file()); if args.status() { println!(" using this config: {:?}", enforcer_cfg); std::process::exit(0); } let cfg_ignores: &Vec<String> = &enforcer_cfg.ignore; let cfg_endings = enforcer_cfg.endings; let file_endings = if !args.endings().is_empty() { args.endings() } else { &cfg_endings }; let mut checked_files: u32 = 0; let mut had_tabs: u32 = 0; let mut had_trailing_ws: u32 = 0; let mut had_illegals: u32 = 0; let mut had_too_long_lines: u32 = 0; let mut had_win_line_endings: u32 = 0;
identifier_body
main.rs
extern crate scoped_pool; #[macro_use] extern crate log; extern crate ansi_term; extern crate env_logger; extern crate pbr; extern crate serde_derive; extern crate term_painter; #[macro_use] extern crate clap; extern crate anyhow; extern crate glob; extern crate num_cpus; extern crate regex; extern crate toml; extern crate unic_char_range; extern crate walkdir; use args::Args; mod app; mod args; mod check; mod clean; mod config; mod search; use pbr::ProgressBar; use std::{ fs::File, io::prelude::*, num, process, sync::{ mpsc::{sync_channel, SyncSender}, Arc, }, thread, }; macro_rules! eprintln { ($($tt:tt)*) => {{ use std::io::Write; let _ = writeln!(&mut ::std::io::stderr(), $($tt)*); }} } #[allow(dead_code)] fn main() { match Args::parse().map(Arc::new).and_then(run) { Ok(0) => process::exit(0), Ok(_) => process::exit(1), Err(err) => { eprintln!("{}", err); process::exit(1); } } } fn run(args: Arc<Args>) -> Result<u64, num::ParseIntError> { let enforcer_cfg = config::get_cfg(args.config_file()); if args.status() { println!(" using this config: {:?}", enforcer_cfg); std::process::exit(0); } let cfg_ignores: &Vec<String> = &enforcer_cfg.ignore; let cfg_endings = enforcer_cfg.endings; let file_endings = if!args.endings().is_empty() { args.endings() } else { &cfg_endings }; let mut checked_files: u32 = 0; let mut had_tabs: u32 = 0; let mut had_trailing_ws: u32 = 0; let mut had_illegals: u32 = 0; let mut had_too_long_lines: u32 = 0; let mut had_win_line_endings: u32 = 0; let clean_f = args.clean(); let tabs_f = args.tabs(); let use_crlf = args.use_crlf(); let thread_count = args.threads(); let color_f = args.color(); let max_line_length = args.line_length(); let start_dir = args.path(); debug!("args:{:?}", args); if args.quiet() { println!("quiet flag was used but is deprecated...use verbosity instead"); } let info_level: check::InfoLevel = args.info_level(); let paths = search::find_matches(start_dir.as_path(), cfg_ignores, file_endings); let count: u64 = paths.len() as u64; let mut pb = ProgressBar::new(count); // logger thread let (logging_tx, logging_rx) = sync_channel::<Option<String>>(0); let stop_logging_tx = logging_tx.clone(); thread::spawn(move || { let mut done = false; while!done { done = logging_rx .recv() .ok() // not done when we got a receive error (sender end of connection closed) .map_or(false, |maybe_print| { maybe_print // a None indicates that logging is done .map_or(true, |p| // just print the string we received {print!("{}", p); false}) }); } }); let (w_chan, r_chan) = sync_channel(thread_count); thread::spawn(move || { use scoped_pool::Pool; let pool = Pool::new(thread_count); pool.scoped(|scope| { for path in paths { let ch: SyncSender<Result<u8, std::io::Error>> = w_chan.clone(); let l_ch: SyncSender<Option<String>> = logging_tx.clone(); scope.execute(move || { if!check::is_dir(path.as_path()) { let p = path.clone(); let mut f = File::open(path) .unwrap_or_else(|_| panic!("error reading file {:?}", p)); let mut buffer = Vec::new(); f.read_to_end(&mut buffer) .unwrap_or_else(|_| panic!("error reading file {:?}", p)); let r = check::check_path( p.as_path(), &buffer, clean_f, info_level, max_line_length, if tabs_f { clean::TabStrategy::Tabify } else { clean::TabStrategy::Untabify }, if use_crlf { clean::LineEnding::CRLF } else { clean::LineEnding::LF }, l_ch, ); ch.send(r).expect("send result with SyncSender"); } }); } }); }); for _ in 0..count { match r_chan.recv() { Ok(res) => match res { Ok(r) => { if (r & check::HAS_TABS) > 0 { had_tabs += 1 } if (r & check::TRAILING_SPACES) > 0 { had_trailing_ws += 1 } if (r & check::HAS_ILLEGAL_CHARACTERS) > 0 { had_illegals += 1 } if (r & check::LINE_TOO_LONG) > 0 { had_too_long_lines += 1 } if (r & check::HAS_WINDOWS_LINE_ENDINGS) > 0 { had_win_line_endings += 1 } } Err(e) => { error!("error occured here: {}", e); } }, Err(e) => { panic!("error in channel: {}", e); } } checked_files += 1; if info_level == check::InfoLevel::Quiet { pb.inc(); } } if info_level == check::InfoLevel::Quiet { pb.finish(); }; let _ = stop_logging_tx.send(None); let findings = Findings { had_tabs, had_trailing_ws, had_illegals, had_too_long_lines, had_win_line_endings, checked_files, }; report_findings(info_level == check::InfoLevel::Quiet, findings, color_f) } #[derive(Debug)] struct Findings { had_tabs: u32, had_trailing_ws: u32, had_illegals: u32, had_too_long_lines: u32, had_win_line_endings: u32, checked_files: u32, } fn
( quiet: bool, findings: Findings, colored: bool, ) -> Result<u64, num::ParseIntError> { let total_errors = findings.had_tabs + findings.had_illegals + findings.had_trailing_ws + findings.had_too_long_lines + findings.had_win_line_endings; if quiet { if colored { println!("{}: {}", check::bold("enforcer-error-count"), total_errors); } else { println!("enforcer-error-count: {}", total_errors); } } if total_errors > 0 { if colored { println!( "checked {} files {}", findings.checked_files, check::bold("(enforcer_errors!)") ); } else { println!( "checked {} files (enforcer_errors!)", findings.checked_files ); } if findings.had_tabs > 0 { println!(" [with TABS:{}]", findings.had_tabs) } if findings.had_illegals > 0 { println!(" [with ILLEGAL CHARS:{}]", findings.had_illegals) } if findings.had_trailing_ws > 0 { println!(" [with TRAILING SPACES:{}]", findings.had_trailing_ws) } if findings.had_too_long_lines > 0 { println!(" [with TOO LONG LINES:{}]", findings.had_too_long_lines) } if findings.had_win_line_endings > 0 { println!( " [with WINDOWS LINE ENDINGS:{}]", findings.had_win_line_endings ) } Ok(1) } else { if colored { println!( "checked {} files {}", findings.checked_files, check::green("(enforcer_clean!)") ); } else { println!("checked {} files (enforcer_clean!)", findings.checked_files); } Ok(0) } }
report_findings
identifier_name
board.rs
extern crate image; use std::fs::File; use std::path::Path; pub struct Board { pub width: usize, pub height: usize, pub data: Vec<String> } impl Board { pub fn new(x: usize, y: usize) -> Board
pub fn colour(&self, x: usize, y: usize) -> (u8,u8,u8) { let s = self.get(x, y); match s.as_ref() { "" => { (255,255,255) } "Y" => { (0,0,255) } "N" => { (255,0,0) } "?" => { (255,255,0) } "t" => { (0,0,0) } _ => { panic!("Unknown sigil: {}", s) } } } pub fn get(&self, x: usize, y: usize) -> String { self.data[ y*self.width + x ].clone() } pub fn set(&mut self, x: usize, y: usize, s: String) { self.data[ y*self.width + x ] = s.clone() } pub fn screenshot(&self, path: String) { let mut imgbuf = image::ImageBuffer::new( self.width as u32, self.height as u32 ); for x in 0.. self.width { for y in 0.. self.height { let (r,g,b) = self.colour(x, y); imgbuf.put_pixel(x as u32, y as u32, image::Rgb([ r, g, b ])); } } let ref mut fout = File::create(&Path::new( &path )).unwrap(); let _ = image::ImageRgb8(imgbuf).save(fout, image::PNG); } }
{ Board { width: x, height: y, data: vec!["".to_string(); x*y] } }
identifier_body
board.rs
extern crate image; use std::fs::File; use std::path::Path; pub struct Board { pub width: usize, pub height: usize, pub data: Vec<String> } impl Board { pub fn new(x: usize, y: usize) -> Board { Board {
} pub fn colour(&self, x: usize, y: usize) -> (u8,u8,u8) { let s = self.get(x, y); match s.as_ref() { "" => { (255,255,255) } "Y" => { (0,0,255) } "N" => { (255,0,0) } "?" => { (255,255,0) } "t" => { (0,0,0) } _ => { panic!("Unknown sigil: {}", s) } } } pub fn get(&self, x: usize, y: usize) -> String { self.data[ y*self.width + x ].clone() } pub fn set(&mut self, x: usize, y: usize, s: String) { self.data[ y*self.width + x ] = s.clone() } pub fn screenshot(&self, path: String) { let mut imgbuf = image::ImageBuffer::new( self.width as u32, self.height as u32 ); for x in 0.. self.width { for y in 0.. self.height { let (r,g,b) = self.colour(x, y); imgbuf.put_pixel(x as u32, y as u32, image::Rgb([ r, g, b ])); } } let ref mut fout = File::create(&Path::new( &path )).unwrap(); let _ = image::ImageRgb8(imgbuf).save(fout, image::PNG); } }
width: x, height: y, data: vec!["".to_string(); x*y] }
random_line_split
board.rs
extern crate image; use std::fs::File; use std::path::Path; pub struct Board { pub width: usize, pub height: usize, pub data: Vec<String> } impl Board { pub fn
(x: usize, y: usize) -> Board { Board { width: x, height: y, data: vec!["".to_string(); x*y] } } pub fn colour(&self, x: usize, y: usize) -> (u8,u8,u8) { let s = self.get(x, y); match s.as_ref() { "" => { (255,255,255) } "Y" => { (0,0,255) } "N" => { (255,0,0) } "?" => { (255,255,0) } "t" => { (0,0,0) } _ => { panic!("Unknown sigil: {}", s) } } } pub fn get(&self, x: usize, y: usize) -> String { self.data[ y*self.width + x ].clone() } pub fn set(&mut self, x: usize, y: usize, s: String) { self.data[ y*self.width + x ] = s.clone() } pub fn screenshot(&self, path: String) { let mut imgbuf = image::ImageBuffer::new( self.width as u32, self.height as u32 ); for x in 0.. self.width { for y in 0.. self.height { let (r,g,b) = self.colour(x, y); imgbuf.put_pixel(x as u32, y as u32, image::Rgb([ r, g, b ])); } } let ref mut fout = File::create(&Path::new( &path )).unwrap(); let _ = image::ImageRgb8(imgbuf).save(fout, image::PNG); } }
new
identifier_name
controller.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/. extern crate rand; use foxbox_core::config_store::ConfigService; use foxbox_core::profile_service::{ProfilePath, ProfileService}; use foxbox_core::traits::Controller; use foxbox_core::upnp::UpnpManager; use foxbox_users::UsersManager; use std::vec::IntoIter; use serde_json; use std::io; use std::net::SocketAddr; use std::net::ToSocketAddrs; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; use tls::{CertificateManager, CertificateRecord, SniSslContextProvider}; use ws; #[derive(Clone)] pub struct ControllerStub { pub config: Arc<ConfigService>, profile_service: Arc<ProfileService>, } impl ControllerStub { pub fn new() -> Self { let path = format!("/tmp/{}", rand::random::<i32>()); let profile_service = ProfileService::new(ProfilePath::Custom(path)); ControllerStub { config: Arc::new(ConfigService::new(&profile_service.path_for("foxbox.conf"))), profile_service: Arc::new(profile_service), } } } impl Default for ControllerStub { fn default() -> Self { ControllerStub::new() } } impl Controller for ControllerStub { fn run(&mut self, _: &AtomicBool) {} fn adapter_started(&self, _: String)
fn adapter_notification(&self, _: serde_json::value::Value) {} fn http_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("localhost", 3000).to_socket_addrs() } fn ws_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("localhost", 4000).to_socket_addrs() } fn add_websocket(&mut self, socket: ws::Sender) {} fn remove_websocket(&mut self, socket: ws::Sender) {} fn broadcast_to_websockets(&self, data: serde_json::value::Value) {} fn get_config(&self) -> Arc<ConfigService> { self.config.clone() } fn get_upnp_manager(&self) -> Arc<UpnpManager> { Arc::new(UpnpManager::new()) } fn get_users_manager(&self) -> Arc<UsersManager> { Arc::new(UsersManager::new(&self.profile_service.path_for("unused"))) } fn get_profile(&self) -> &ProfileService { &self.profile_service } fn get_tls_enabled(&self) -> bool { false } fn get_hostname(&self) -> String { String::from("localhost") } fn get_domain(&self) -> String { String::from("knilox.org") } fn get_box_certificate(&self) -> io::Result<CertificateRecord> { CertificateRecord::new_from_components("foxbox.local".to_owned(), PathBuf::from("a/file.pem"), PathBuf::from("b/file.pem"), "abcdef".to_owned()) } fn get_certificate_manager(&self) -> CertificateManager { CertificateManager::new(PathBuf::from(current_dir!()), "knilxof.org", Box::new(SniSslContextProvider::new())) } }
{}
identifier_body
controller.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/. extern crate rand; use foxbox_core::config_store::ConfigService; use foxbox_core::profile_service::{ProfilePath, ProfileService}; use foxbox_core::traits::Controller; use foxbox_core::upnp::UpnpManager; use foxbox_users::UsersManager; use std::vec::IntoIter; use serde_json; use std::io; use std::net::SocketAddr; use std::net::ToSocketAddrs; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; use tls::{CertificateManager, CertificateRecord, SniSslContextProvider}; use ws; #[derive(Clone)] pub struct ControllerStub { pub config: Arc<ConfigService>, profile_service: Arc<ProfileService>, } impl ControllerStub { pub fn new() -> Self { let path = format!("/tmp/{}", rand::random::<i32>()); let profile_service = ProfileService::new(ProfilePath::Custom(path)); ControllerStub { config: Arc::new(ConfigService::new(&profile_service.path_for("foxbox.conf"))), profile_service: Arc::new(profile_service), } } } impl Default for ControllerStub { fn default() -> Self { ControllerStub::new() } } impl Controller for ControllerStub { fn run(&mut self, _: &AtomicBool) {} fn adapter_started(&self, _: String) {} fn adapter_notification(&self, _: serde_json::value::Value) {} fn http_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("localhost", 3000).to_socket_addrs() } fn ws_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("localhost", 4000).to_socket_addrs() } fn add_websocket(&mut self, socket: ws::Sender) {} fn remove_websocket(&mut self, socket: ws::Sender) {} fn broadcast_to_websockets(&self, data: serde_json::value::Value) {}
} fn get_upnp_manager(&self) -> Arc<UpnpManager> { Arc::new(UpnpManager::new()) } fn get_users_manager(&self) -> Arc<UsersManager> { Arc::new(UsersManager::new(&self.profile_service.path_for("unused"))) } fn get_profile(&self) -> &ProfileService { &self.profile_service } fn get_tls_enabled(&self) -> bool { false } fn get_hostname(&self) -> String { String::from("localhost") } fn get_domain(&self) -> String { String::from("knilox.org") } fn get_box_certificate(&self) -> io::Result<CertificateRecord> { CertificateRecord::new_from_components("foxbox.local".to_owned(), PathBuf::from("a/file.pem"), PathBuf::from("b/file.pem"), "abcdef".to_owned()) } fn get_certificate_manager(&self) -> CertificateManager { CertificateManager::new(PathBuf::from(current_dir!()), "knilxof.org", Box::new(SniSslContextProvider::new())) } }
fn get_config(&self) -> Arc<ConfigService> { self.config.clone()
random_line_split
controller.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/. extern crate rand; use foxbox_core::config_store::ConfigService; use foxbox_core::profile_service::{ProfilePath, ProfileService}; use foxbox_core::traits::Controller; use foxbox_core::upnp::UpnpManager; use foxbox_users::UsersManager; use std::vec::IntoIter; use serde_json; use std::io; use std::net::SocketAddr; use std::net::ToSocketAddrs; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::AtomicBool; use tls::{CertificateManager, CertificateRecord, SniSslContextProvider}; use ws; #[derive(Clone)] pub struct ControllerStub { pub config: Arc<ConfigService>, profile_service: Arc<ProfileService>, } impl ControllerStub { pub fn new() -> Self { let path = format!("/tmp/{}", rand::random::<i32>()); let profile_service = ProfileService::new(ProfilePath::Custom(path)); ControllerStub { config: Arc::new(ConfigService::new(&profile_service.path_for("foxbox.conf"))), profile_service: Arc::new(profile_service), } } } impl Default for ControllerStub { fn default() -> Self { ControllerStub::new() } } impl Controller for ControllerStub { fn run(&mut self, _: &AtomicBool) {} fn adapter_started(&self, _: String) {} fn adapter_notification(&self, _: serde_json::value::Value) {} fn http_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("localhost", 3000).to_socket_addrs() } fn ws_as_addrs(&self) -> Result<IntoIter<SocketAddr>, io::Error> { ("localhost", 4000).to_socket_addrs() } fn add_websocket(&mut self, socket: ws::Sender) {} fn remove_websocket(&mut self, socket: ws::Sender) {} fn broadcast_to_websockets(&self, data: serde_json::value::Value) {} fn get_config(&self) -> Arc<ConfigService> { self.config.clone() } fn get_upnp_manager(&self) -> Arc<UpnpManager> { Arc::new(UpnpManager::new()) } fn get_users_manager(&self) -> Arc<UsersManager> { Arc::new(UsersManager::new(&self.profile_service.path_for("unused"))) } fn get_profile(&self) -> &ProfileService { &self.profile_service } fn get_tls_enabled(&self) -> bool { false } fn
(&self) -> String { String::from("localhost") } fn get_domain(&self) -> String { String::from("knilox.org") } fn get_box_certificate(&self) -> io::Result<CertificateRecord> { CertificateRecord::new_from_components("foxbox.local".to_owned(), PathBuf::from("a/file.pem"), PathBuf::from("b/file.pem"), "abcdef".to_owned()) } fn get_certificate_manager(&self) -> CertificateManager { CertificateManager::new(PathBuf::from(current_dir!()), "knilxof.org", Box::new(SniSslContextProvider::new())) } }
get_hostname
identifier_name
snapshot_manifest.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Snapshot manifest type definition use util::hash::H256; use rlp::*; use util::Bytes; /// Manifest data. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct ManifestData { /// List of state chunk hashes. pub state_hashes: Vec<H256>, /// List of block chunk hashes. pub block_hashes: Vec<H256>, /// The final, expected state root. pub state_root: H256, /// Block number this snapshot was taken at. pub block_number: u64, /// Block hash this snapshot was taken at. pub block_hash: H256, } impl ManifestData { /// Encode the manifest data to rlp. pub fn into_rlp(self) -> Bytes { let mut stream = RlpStream::new_list(5); stream.append(&self.state_hashes); stream.append(&self.block_hashes); stream.append(&self.state_root); stream.append(&self.block_number); stream.append(&self.block_hash); stream.out() } /// Try to restore manifest data from raw bytes, interpreted as RLP. pub fn from_rlp(raw: &[u8]) -> Result<Self, DecoderError>
}
{ let decoder = UntrustedRlp::new(raw); let state_hashes: Vec<H256> = decoder.val_at(0)?; let block_hashes: Vec<H256> = decoder.val_at(1)?; let state_root: H256 = decoder.val_at(2)?; let block_number: u64 = decoder.val_at(3)?; let block_hash: H256 = decoder.val_at(4)?; Ok(ManifestData { state_hashes: state_hashes, block_hashes: block_hashes, state_root: state_root, block_number: block_number, block_hash: block_hash, }) }
identifier_body
snapshot_manifest.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Snapshot manifest type definition use util::hash::H256; use rlp::*;
pub struct ManifestData { /// List of state chunk hashes. pub state_hashes: Vec<H256>, /// List of block chunk hashes. pub block_hashes: Vec<H256>, /// The final, expected state root. pub state_root: H256, /// Block number this snapshot was taken at. pub block_number: u64, /// Block hash this snapshot was taken at. pub block_hash: H256, } impl ManifestData { /// Encode the manifest data to rlp. pub fn into_rlp(self) -> Bytes { let mut stream = RlpStream::new_list(5); stream.append(&self.state_hashes); stream.append(&self.block_hashes); stream.append(&self.state_root); stream.append(&self.block_number); stream.append(&self.block_hash); stream.out() } /// Try to restore manifest data from raw bytes, interpreted as RLP. pub fn from_rlp(raw: &[u8]) -> Result<Self, DecoderError> { let decoder = UntrustedRlp::new(raw); let state_hashes: Vec<H256> = decoder.val_at(0)?; let block_hashes: Vec<H256> = decoder.val_at(1)?; let state_root: H256 = decoder.val_at(2)?; let block_number: u64 = decoder.val_at(3)?; let block_hash: H256 = decoder.val_at(4)?; Ok(ManifestData { state_hashes: state_hashes, block_hashes: block_hashes, state_root: state_root, block_number: block_number, block_hash: block_hash, }) } }
use util::Bytes; /// Manifest data. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)]
random_line_split
snapshot_manifest.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. //! Snapshot manifest type definition use util::hash::H256; use rlp::*; use util::Bytes; /// Manifest data. #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "ipc", binary)] pub struct
{ /// List of state chunk hashes. pub state_hashes: Vec<H256>, /// List of block chunk hashes. pub block_hashes: Vec<H256>, /// The final, expected state root. pub state_root: H256, /// Block number this snapshot was taken at. pub block_number: u64, /// Block hash this snapshot was taken at. pub block_hash: H256, } impl ManifestData { /// Encode the manifest data to rlp. pub fn into_rlp(self) -> Bytes { let mut stream = RlpStream::new_list(5); stream.append(&self.state_hashes); stream.append(&self.block_hashes); stream.append(&self.state_root); stream.append(&self.block_number); stream.append(&self.block_hash); stream.out() } /// Try to restore manifest data from raw bytes, interpreted as RLP. pub fn from_rlp(raw: &[u8]) -> Result<Self, DecoderError> { let decoder = UntrustedRlp::new(raw); let state_hashes: Vec<H256> = decoder.val_at(0)?; let block_hashes: Vec<H256> = decoder.val_at(1)?; let state_root: H256 = decoder.val_at(2)?; let block_number: u64 = decoder.val_at(3)?; let block_hash: H256 = decoder.val_at(4)?; Ok(ManifestData { state_hashes: state_hashes, block_hashes: block_hashes, state_root: state_root, block_number: block_number, block_hash: block_hash, }) } }
ManifestData
identifier_name
p_2_3_1_01.rs
// P_2_3_1_01 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung.de // // 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. /** * draw tool. draw with a rotating line. * * MOUSE * drag : draw * * KEYS * 1-4 : switch default colors * delete/backspace : clear screen * d : reverse direction and mirror angle * space : new random color * arrow left : rotation speed - * arrow right : rotation speed + * arrow up : line length + * arrow down : line length - * s : save png */ use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Mod
c: Rgba, line_length: f32, angle: f32, angle_speed: f32, } fn model(app: &App) -> Model { app.new_window() .size(1280, 720) .view(view) .mouse_pressed(mouse_pressed) .key_pressed(key_pressed) .key_released(key_released) .build() .unwrap(); Model { c: rgba(0.7, 0.6, 0.0, 1.0), line_length: 0.0, angle: 0.0, angle_speed: 1.0, } } fn update(app: &App, model: &mut Model, _update: Update) { if app.mouse.buttons.left().is_down() { model.angle += model.angle_speed; } } fn view(app: &App, model: &Model, frame: Frame) { let mut draw = app.draw(); if frame.nth() == 0 || app.keys.down.contains(&Key::Delete) { frame.clear(WHITE); } if app.mouse.buttons.left().is_down() { draw = draw .x_y(app.mouse.x, app.mouse.y) .rotate(model.angle.to_radians()); draw.line() .start(pt2(0.0, 0.0)) .end(pt2(model.line_length, 0.0)) .color(model.c); } // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) { model.line_length = random_range(70.0, 200.0); } fn key_pressed(_app: &App, model: &mut Model, key: Key) { match key { Key::Up => { model.line_length += 5.0; } Key::Down => { model.line_length -= 5.0; } Key::Left => { model.angle_speed -= 0.5; } Key::Right => { model.angle_speed += 0.5; } _otherkey => (), } } fn key_released(app: &App, model: &mut Model, key: Key) { match key { Key::S => { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } // reverse direction and mirror angle Key::D => { model.angle += 180.0; model.angle_speed *= -1.0; } // change color Key::Space => { model.c = rgba( random_f32(), random_f32(), random_f32(), random_range(0.3, 0.4), ); } // default colors from 1 to 4 Key::Key1 => { model.c = rgba(0.7, 0.61, 0.0, 1.0); } Key::Key2 => { model.c = rgba(0.0, 0.5, 0.64, 1.0); } Key::Key3 => { model.c = rgba(0.34, 0.13, 0.5, 1.0); } Key::Key4 => { model.c = rgba(0.77, 0.0, 0.48, 1.0); } _otherkey => (), } }
el {
identifier_name