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
utils.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
pub fn merge(&mut self, other: Self) { *self = self.join(other); } } pub fn change_loop<F>(mut func: F) where F: FnMut() -> WasChanged, { while let WasChanged::Changed = func() {} } pub fn change_iter<I, F>(iter: I, mut func: F) -> WasChanged where I: IntoIterator, F: FnMut(I::Item) -> WasChanged, {...
{ match (self, other) { (WasChanged::Changed, _) | (_, WasChanged::Changed) => { WasChanged::Changed } _ => WasChanged::Unchanged, } }
identifier_body
utils.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} /// A refcounted name type, used to avoid duplicating common string values /// throughout an AST. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Name(std::rc::Rc<String>); impl Name { /// Creates a new Name containing the given string. pub fn new(s: &(impl AsRef<str> +?Sized)) -> Self { N...
iter .next() .and_then(|v| if iter.next().is_some() { None } else { Some(v) })
random_line_split
utils.rs
// Copyright 2019 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
(std::rc::Rc<String>); impl Name { /// Creates a new Name containing the given string. pub fn new(s: &(impl AsRef<str> +?Sized)) -> Self { Name(std::rc::Rc::new(s.as_ref().to_string())) } /// Returns a reference to the internal ref. pub fn str(&self) -> &str { &**self.0 } /// Returns a mutable ...
Name
identifier_name
htmlmetaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLMetaElementBin...
pub fn get_cssom_stylesheet(&self) -> Option<Root<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), ...
{ self.stylesheet.borrow().clone() }
identifier_body
htmlmetaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLMetaElementBin...
(&self) { if!PREFS.get("layout.viewport.enabled").as_boolean().unwrap_or(false) { return; } let element = self.upcast::<Element>(); if let Some(content) = element.get_attribute(&ns!(), &local_name!("content")).r() { let content = content.value(); if!co...
apply_viewport
identifier_name
htmlmetaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLMetaElementBin...
} }
{ self.process_referrer_attribute(); }
conditional_block
htmlmetaelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLMetaElementBin...
self.process_referrer_attribute(); } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { self.process_referrer_attribute(); } } }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { if let Some(s) = self.super_type() { s.attribute_mutated(attr, mutation); }
random_line_split
traits.rs
use std::io::{BufReader, BufRead, Seek, Cursor}; use std::fs::File; use std::path::Path; use types::Result; /// Provides several convenience functions for loading metadata from various sources. pub trait LoadableMetadata: Sized { /// Loads the implementing type from the given buffered input stream. fn load<R:...
/// Loads the implementing type from an in-memory buffer. /// /// Delegates to `LoadableMetadata::load_from_seek()` method by default. #[inline] fn load_from_buf(buf: &[u8]) -> Result<Self> { LoadableMetadata::load_from_seek(&mut Cursor::new(buf)) } }
{ let mut f = BufReader::new(try!(File::open(path))); LoadableMetadata::load_from_seek(&mut f) }
identifier_body
traits.rs
use std::io::{BufReader, BufRead, Seek, Cursor}; use std::fs::File; use std::path::Path; use types::Result; /// Provides several convenience functions for loading metadata from various sources. pub trait LoadableMetadata: Sized { /// Loads the implementing type from the given buffered input stream. fn load<R:...
/// /// Delegates to `LoadableMetadata::load_from_seek()` method by default. #[inline] fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self> { let mut f = BufReader::new(try!(File::open(path))); LoadableMetadata::load_from_seek(&mut f) } /// Loads the implementing type from...
} /// Loads the implementing type from a file specified by the given path.
random_line_split
traits.rs
use std::io::{BufReader, BufRead, Seek, Cursor}; use std::fs::File; use std::path::Path; use types::Result; /// Provides several convenience functions for loading metadata from various sources. pub trait LoadableMetadata: Sized { /// Loads the implementing type from the given buffered input stream. fn load<R:...
(buf: &[u8]) -> Result<Self> { LoadableMetadata::load_from_seek(&mut Cursor::new(buf)) } }
load_from_buf
identifier_name
lib.rs
//! Serde Serialization Framework //! //! Serde is a powerful framework that enables serialization libraries to generically serialize //! Rust data structures without the overhead of runtime type information. In many situations, the
//! type. //! //! For a detailed tutorial on the different ways to use serde please check out the //! [github repository](https://github.com/serde-rs/serde) #![doc(html_root_url="https://serde-rs.github.io/serde/serde")] #![cfg_attr(feature = "nightly", feature(collections, enumset, nonzero, plugin, step_trait, ...
//! handshake protocol between serializers and serializees can be completely optimized away, //! leaving serde to perform roughly the same speed as a hand written serializer for a specific
random_line_split
class-poly-methods-cross-crate.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 ...
() { let mut nyan : cat<char> = cat::<char>(52u, 99, ~['p']); let mut kitty = cat(1000u, 2, ~[~"tabby"]); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); nyan.speak(~[1u,2u,3u]); assert_eq!(nyan.meow_count(), 55u); kitty.speak(~[~"meow", ~"mew", ~"purr", ~"chirp"]); assert_eq!(kitty.me...
main
identifier_name
class-poly-methods-cross-crate.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 ...
nyan.speak(~[1u,2u,3u]); assert_eq!(nyan.meow_count(), 55u); kitty.speak(~[~"meow", ~"mew", ~"purr", ~"chirp"]); assert_eq!(kitty.meow_count(), 1004u); }
assert_eq!(kitty.how_hungry, 2);
random_line_split
class-poly-methods-cross-crate.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 ...
{ let mut nyan : cat<char> = cat::<char>(52u, 99, ~['p']); let mut kitty = cat(1000u, 2, ~[~"tabby"]); assert_eq!(nyan.how_hungry, 99); assert_eq!(kitty.how_hungry, 2); nyan.speak(~[1u,2u,3u]); assert_eq!(nyan.meow_count(), 55u); kitty.speak(~[~"meow", ~"mew", ~"purr", ~"chirp"]); assert_eq!(kitty.meow_...
identifier_body
unify.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-MI...
/// Either redirects node_a to node_b or vice versa, depending on the relative rank. Returns /// the new root and rank. You should then update the value of the new root to something /// suitable. pub fn unify(&mut self, tcx: &ty::ctxt<'tcx>, node_a: &Node<K,V>, ...
{ assert!(self.is_root(&key)); debug!("Updating variable {} to {}", key.repr(tcx), new_value.repr(tcx)); self.values.set(key.index(), new_value); }
identifier_body
unify.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-MI...
(&mut self, snapshot: Snapshot<K>) { debug!("{}: commit()", UnifyKey::tag(None::<K>)); self.values.commit(snapshot.snapshot); } pub fn new_key(&mut self, value: V) -> K { let index = self.values.push(Root(value, 0)); let k = UnifyKey::from_index(index); debug!("{}: creat...
commit
identifier_name
unify.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-MI...
/// Trait for valid types that a type variable can be set to. Note that /// this is typically not the end type that the value will take on, but /// rather an `Option` wrapper (where `None` represents a variable /// whose value is not yet set). /// /// Implementations of this trait are at the end of this file. pub trait...
fn tag(k: Option<Self>) -> &'static str; }
random_line_split
system_clock.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
#[inline(always)] fn write_pll0_changes() { reg::PLL0FEED.set_value(0xaa); reg::PLL0FEED.set_value(0x55); } #[inline(always)] fn init_pll(pll: &PLL0, source: &ClockSource) { use self::ClockSource::*; match source { &Internal => reg::CLKSRCSEL.set_value(0), &Main(_) => reg::CLKSRCSEL.set_value(1), ...
{ wait_for!(reg::PLL0STAT.value() & (1 << bit) == (1 << bit)); }
identifier_body
system_clock.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
/// PLL clock source. #[derive(Copy)] pub enum ClockSource { /// Internal resonator, 4MHz. Internal, /// External crystal with configurable frequency. Main(u32), /// Internal RTC resonator, 32KHz. RTC, } /// PLL0 configuration options. /// /// Frequency is calculated as /// /// ``` /// Fcco = (2 * m * Fin...
#[macro_use] mod ioreg; #[path="../../util/wait_for.rs"] #[macro_use] mod wait_for;
random_line_split
system_clock.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
(freq: u32) { let num_clocks: u32 = if freq > 100_000_000 { 6 } else if freq > 80_000_000 { 5 } else if freq > 60_000_000 { 4 } else if freq > 40_000_000 { 3 } else if freq > 20_000_000 { 2 } else {...
init_flash_access
identifier_name
system_clock.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
, None => { dst_clock = src_clock; }, } unsafe { SystemClock = dst_clock }; } #[inline(always)] fn init_main_oscillator(freq: u32) { let val: u32 = if freq > 15_000_000 { 1 << 4 } else { 0 } | (1 << 5); reg::SCS.set_value(val); wait_for!(reg::SCS.value() & (1 << 6) == (1 << 6)); } #[...
{ match clock.source { Main(freq) => init_main_oscillator(freq), _ => (), } dst_clock = (src_clock * pll.m as u32 * 2) / pll.n as u32 / pll.divisor as u32; init_flash_access(dst_clock); init_pll(pll, &clock.source); }
conditional_block
main.rs
// Get a slice out of Array a where the??? is so that the `if` statement // returns true. Scroll down for hints!! fn main() { let a = [1, 2, 3, 4, 5]; let nice_slice = &a[1..4]; if nice_slice == [2, 3, 4]
else { println!("Not quite what I was expecting... I see: {:?}", nice_slice); } } // Take a look at the Primitive Types -> Slices section of the book: // http://doc.rust-lang.org/stable/book/primitive-types.html#slices // and use the starting and ending indices of the items in the Array // that you want t...
{ println!("Nice slice!"); }
conditional_block
main.rs
// Get a slice out of Array a where the??? is so that the `if` statement // returns true. Scroll down for hints!! fn
() { let a = [1, 2, 3, 4, 5]; let nice_slice = &a[1..4]; if nice_slice == [2, 3, 4] { println!("Nice slice!"); } else { println!("Not quite what I was expecting... I see: {:?}", nice_slice); } } // Take a look at the Primitive Types -> Slices section of the book: // http://doc.rus...
main
identifier_name
main.rs
// Get a slice out of Array a where the??? is so that the `if` statement // returns true. Scroll down for hints!!
if nice_slice == [2, 3, 4] { println!("Nice slice!"); } else { println!("Not quite what I was expecting... I see: {:?}", nice_slice); } } // Take a look at the Primitive Types -> Slices section of the book: // http://doc.rust-lang.org/stable/book/primitive-types.html#slices // and use the ...
fn main() { let a = [1, 2, 3, 4, 5]; let nice_slice = &a[1..4];
random_line_split
main.rs
// Get a slice out of Array a where the??? is so that the `if` statement // returns true. Scroll down for hints!! fn main()
// Take a look at the Primitive Types -> Slices section of the book: // http://doc.rust-lang.org/stable/book/primitive-types.html#slices // and use the starting and ending indices of the items in the Array // that you want to end up in the slice. // If you're curious why the right hand of the `==` comparison does no...
{ let a = [1, 2, 3, 4, 5]; let nice_slice = &a[1..4]; if nice_slice == [2, 3, 4] { println!("Nice slice!"); } else { println!("Not quite what I was expecting... I see: {:?}", nice_slice); } }
identifier_body
mod.rs
plan::BuildPlan; mod unit_dependencies; use self::unit_dependencies::build_unit_dependencies; mod compilation_files; pub use self::compilation_files::{Metadata, OutputFile}; use self::compilation_files::CompilationFiles; /// All information needed to define a Unit. /// /// A unit is an object that has enough informa...
(&mut self) -> CargoResult<()> { let _p = profile::start("preparing layout"); self.files_mut() .host .prepare() .chain_err(|| internal("couldn't prepare build directories"))?; if let Some(ref mut target) = self.files.as_mut().unwrap().target { target...
prepare
identifier_name
mod.rs
::BuildPlan; mod unit_dependencies; use self::unit_dependencies::build_unit_dependencies; mod compilation_files; pub use self::compilation_files::{Metadata, OutputFile}; use self::compilation_files::CompilationFiles; /// All information needed to define a Unit. /// /// A unit is an object that has enough information...
; let host_layout = Layout::new(self.bcx.ws, None, dest)?; let target_layout = match self.bcx.build_config.requested_target.as_ref() { Some(target) => Some(Layout::new(self.bcx.ws, Some(target), dest)?), None => None, }; build_unit_dependencies(units, self.bcx, &...
{ "debug" }
conditional_block
mod.rs
plan::BuildPlan; mod unit_dependencies; use self::unit_dependencies::build_unit_dependencies; mod compilation_files; pub use self::compilation_files::{Metadata, OutputFile}; use self::compilation_files::CompilationFiles; /// All information needed to define a Unit. /// /// A unit is an object that has enough informa...
// have it enabled by default while release profiles have it disabled // by default. let global_cfg = self.bcx .config .get_bool("build.incremental")? .map(|c| c.val); let incremental = match ( self.bcx.incremental_env, global_...
{ // There's a number of ways to configure incremental compilation right // now. In order of descending priority (first is highest priority) we // have: // // * `CARGO_INCREMENTAL` - this is blanket used unconditionally to turn // on/off incremental compilation for any ...
identifier_body
mod.rs
_plan::BuildPlan; mod unit_dependencies; use self::unit_dependencies::build_unit_dependencies; mod compilation_files; pub use self::compilation_files::{Metadata, OutputFile}; use self::compilation_files::CompilationFiles; /// All information needed to define a Unit. /// /// A unit is an object that has enough inform...
// Now that we've figured out everything that we're going to do, do it! queue.execute(&mut self, &mut plan)?; if build_plan { plan.set_inputs(self.bcx.inputs()?); plan.output_plan(); } for unit in units.iter() { for output in self.outputs(uni...
// function which will run everything in order with proper // parallelism. super::compile(&mut self, &mut queue, &mut plan, unit, exec)?; }
random_line_split
server.rs
use rocket_contrib::templates::handlebars::Handlebars; use std::panic::catch_unwind; pub fn serve() { // in debug builds this will force an init, good enough for testing let _hbars = &*TEMPLATES; loop { let port = std::env::var("ROCKET_PORT").unwrap_or_else(|_| String::from("OOPS")); info!...
( username: String, ) -> DashResult<Json<(GitHubUser, Vec<nag::IndividualFcp>)>> { Ok(Json(nag::individual_nags(&username)?)) } #[post("/github-webhook", data = "<event>")] pub fn github_webhook(event: Event) -> DashResult<()> { let conn = &*DB_POOL.get()?; match event....
member_fcps
identifier_name
server.rs
use rocket_contrib::templates::handlebars::Handlebars; use std::panic::catch_unwind; pub fn serve() { // in debug builds this will force an init, good enough for testing let _hbars = &*TEMPLATES; loop { let port = std::env::var("ROCKET_PORT").unwrap_or_else(|_| String::from("OOPS")); info!...
} mod api { use crate::domain::github::GitHubUser; use crate::error::DashResult; use crate::github::webhooks::{Event, Payload}; use crate::github::{handle_comment, handle_issue, handle_pr}; use crate::nag; use crate::DB_POOL; use rocket_contrib::json::Json; #[get("/all")] pub fn al...
random_line_split
server.rs
use rocket_contrib::templates::handlebars::Handlebars; use std::panic::catch_unwind; pub fn serve() { // in debug builds this will force an init, good enough for testing let _hbars = &*TEMPLATES; loop { let port = std::env::var("ROCKET_PORT").unwrap_or_else(|_| String::from("OOPS")); info!...
#[get("/<username>")] pub fn member_fcps( username: String, ) -> DashResult<Json<(GitHubUser, Vec<nag::IndividualFcp>)>> { Ok(Json(nag::individual_nags(&username)?)) } #[post("/github-webhook", data = "<event>")] pub fn github_webhook(event: Event) -> DashResult<()> { ...
{ Ok(Json(nag::all_fcps()?)) }
identifier_body
server.rs
use rocket_contrib::templates::handlebars::Handlebars; use std::panic::catch_unwind; pub fn serve() { // in debug builds this will force an init, good enough for testing let _hbars = &*TEMPLATES; loop { let port = std::env::var("ROCKET_PORT").unwrap_or_else(|_| String::from("OOPS")); info!...
} Payload::Unsupported => (), } Ok(()) } } lazy_static! { static ref TEMPLATES: Handlebars = { let mut hbars = Handlebars::new(); let root_template = include_str!("templates/index.html"); let all_fcps_fragment = include_str!("templates/fcp.hbs...
{ // TODO handle deleted comments properly handle_issue( conn, comment_event.issue, &comment_event.repository.full_name, )?; handle_comment( con...
conditional_block
loader.rs
&CrateMismatch{ ref path,.. }) in mismatches.enumerate() { self.sess.fileline_note(self.span, &format!("crate `{}` path #{}: {}", self.ident, i+1, path.display())); } match self.root { &None => {} &S...
as_slice
identifier_name
loader.rs
} else { dylibs.insert(p, kind); } FileMatches }).unwrap_or(FileDoesntMatch) }); self.rejected_via_kind.extend(staticlibs); // We have now collected all known libraries into a set of candidates // keyed of the ...
{ if target.options.is_like_osx { "__DATA,__note.rustc" } else if target.options.is_like_msvc { // When using link.exe it was seen that the section name `.note.rustc` // was getting shortened to `.note.ru`, and according to the PE and COFF // specification: // // ...
identifier_body
loader.rs
//! dependency graph: //! //! ```text //! A.1 A.2 //! | | //! | | //! B C //! \ / //! \ / //! D //! ``` //! //! In this scenario, when we compile `D`, we need to be able to distinctly //! resolve `A.1` and `A.2`, but an `--extern` flag cannot apply to these //! transitive dependencies. //! //! Not...
use metadata::encoder; use metadata::filesearch::{FileSearch, FileMatches, FileDoesntMatch}; use syntax::codemap::Span; use syntax::diagnostic::SpanHandler; use util::common; use rustc_back::target::Target; use std::cmp; use std::collections::HashMap; use std::fs; use std::io::prelude::*; use std::io; use std::path::{...
use llvm; use llvm::{False, ObjectFile, mk_section_iter}; use llvm::archive_ro::ArchiveRO; use metadata::cstore::{MetadataBlob, MetadataVec, MetadataArchive}; use metadata::decoder;
random_line_split
machine.rs
use std::io::stdio::{stdin_raw, stdout_raw}; use storage::{Tape, VectorTape}; use operators::{Sub, Incr, Decr, Prev, Next, Put, Get}; use ast::Ast; /** A brainfuck interpreter machine. Models the internal state of a Brainfuck machine. It is a simple tape machine with a program counter representing the current operat...
while *self.tape.cell()!= 0 { match self.run_program(ast) { Ok(cls) => cycles += cls, Err(msg) => return Err(msg), } } self.pc = pc; // Restore PC } // Unknown. Nop. Some(_) => { /* nop */ }, // End of program. Stop execution. _ => break } // Track this...
// Executes a sub-AST. If the current cell's value // is zero, the ops in the sub-AST will be executed, // else skipping them entirely. Some(&Sub(ref ast)) => { let pc = self.pc; // Save PC and reset
random_line_split
machine.rs
use std::io::stdio::{stdin_raw, stdout_raw}; use storage::{Tape, VectorTape}; use operators::{Sub, Incr, Decr, Prev, Next, Put, Get}; use ast::Ast; /** A brainfuck interpreter machine. Models the internal state of a Brainfuck machine. It is a simple tape machine with a program counter representing the current operat...
{ /// A tape to be used as the main storage. tape: VectorTape<u8>, /// Program counter pointing at the current operator. pc: uint, } impl Machine { // Produce a new pristine machine. pub fn new() -> Machine { Machine { tape: VectorTape::new(), pc: 0, } } /** Run a program, given in the form of a ...
Machine
identifier_name
machine.rs
use std::io::stdio::{stdin_raw, stdout_raw}; use storage::{Tape, VectorTape}; use operators::{Sub, Incr, Decr, Prev, Next, Put, Get}; use ast::Ast; /** A brainfuck interpreter machine. Models the internal state of a Brainfuck machine. It is a simple tape machine with a program counter representing the current operat...
/** Run a program, given in the form of a parsed AST, on this machine's tape. Will return the cycles that have been executed. */ pub fn run_program<'a>(&mut self, program: &Ast) -> Result<uint, ~str> { self.pc = 0; // Begin interpreting at the start of the AST. let mut cycles: uint = 0; // Keep track of the ...
{ Machine { tape: VectorTape::new(), pc: 0, } }
identifier_body
machine.rs
use std::io::stdio::{stdin_raw, stdout_raw}; use storage::{Tape, VectorTape}; use operators::{Sub, Incr, Decr, Prev, Next, Put, Get}; use ast::Ast; /** A brainfuck interpreter machine. Models the internal state of a Brainfuck machine. It is a simple tape machine with a program counter representing the current operat...
, // End of program. Stop execution. _ => break } // Track this last cycle and advance to the next operator. cycles += 1; self.pc += 1; } // Everything went well. Just return the stats back. Ok(cycles) } }
{ /* nop */ }
conditional_block
error.rs
use std::error; use std::fmt; pub type RResult<T, E> where E: error::Error = Result<T, E>; #[derive(Debug, PartialEq)] pub enum RLispError { EvalError(EvalError), ParseError(ParseError), } impl fmt::Display for RLispError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ...
{ E, // must be fix UnknowSymbol(String), InvalidArgNumber, WrongTypeArg, } impl fmt::Display for EvalError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { EvalError::E => write!(f, "eval error must be fix"), EvalError::UnknowSymbol(ref s) => ...
EvalError
identifier_name
error.rs
use std::error; use std::fmt; pub type RResult<T, E> where E: error::Error = Result<T, E>; #[derive(Debug, PartialEq)] pub enum RLispError { EvalError(EvalError), ParseError(ParseError), }
impl fmt::Display for RLispError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RLispError::EvalError(ref e) => write!(f, "Eval Error: {}", e), RLispError::ParseError(ref e) => write!(f, "Parse Error: {}", e), } } } impl error::Error for RLispErr...
random_line_split
error.rs
use std::error; use std::fmt; pub type RResult<T, E> where E: error::Error = Result<T, E>; #[derive(Debug, PartialEq)] pub enum RLispError { EvalError(EvalError), ParseError(ParseError), } impl fmt::Display for RLispError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ...
} #[derive(Debug, PartialEq)] pub enum EvalError { E, // must be fix UnknowSymbol(String), InvalidArgNumber, WrongTypeArg, } impl fmt::Display for EvalError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { EvalError::E => write!(f, "eval error must be fix...
{ "" }
identifier_body
bear.rs
extern crate rustc_serialize; extern crate docopt; use std::fs::File; use std::path::Path; use memory::Memory; use interpret::interpret; use docopt::Docopt; use std::io; mod memory; mod interpret; #[derive(RustcDecodable)] struct BearOpts { flag_file: Option<String>, flag_help: bool, flag_interactive: b...
fn main() { use std::io::Read; let opts: BearOpts = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if opts.flag_help { println!("{}", USAGE); } else if opts.flag_interactive { interactive_console(&o...
{ use std::io::BufRead; let mut mem = Memory::new(); println!("BEAR Interactive Console ver. 1.0"); print!("> "); let stdin = io::stdin(); for line in stdin.lock().lines() { match line { Ok(val) => { interpret(val, &mut mem, opts.flag_debug); print!("\n> "); }, ...
identifier_body
bear.rs
extern crate rustc_serialize; extern crate docopt; use std::fs::File; use std::path::Path; use memory::Memory; use interpret::interpret; use docopt::Docopt; use std::io; mod memory; mod interpret; #[derive(RustcDecodable)] struct BearOpts { flag_file: Option<String>,
flag_help: bool, flag_interactive: bool, flag_debug: bool } const USAGE: &'static str = " BEAR - Another BF. USAGE: bear (-f FILE | --file FILE | -i | --interactive) [-d | --debug] bear (-h | --help) Options: -h, --help Show usage description. -f FILE, --file FILE Read file and interpre...
random_line_split
bear.rs
extern crate rustc_serialize; extern crate docopt; use std::fs::File; use std::path::Path; use memory::Memory; use interpret::interpret; use docopt::Docopt; use std::io; mod memory; mod interpret; #[derive(RustcDecodable)] struct BearOpts { flag_file: Option<String>, flag_help: bool, flag_interactive: b...
else { let filename = match opts.flag_file { Some(val) => val, None => panic!("--file required") }; let test = match File::open(&Path::new(&filename)) { Ok(mut val) => { let mut s = String::new(); val.read_to_string(&mut s)...
{ interactive_console(&opts); }
conditional_block
bear.rs
extern crate rustc_serialize; extern crate docopt; use std::fs::File; use std::path::Path; use memory::Memory; use interpret::interpret; use docopt::Docopt; use std::io; mod memory; mod interpret; #[derive(RustcDecodable)] struct BearOpts { flag_file: Option<String>, flag_help: bool, flag_interactive: b...
() { use std::io::Read; let opts: BearOpts = Docopt::new(USAGE) .and_then(|d| d.decode()) .unwrap_or_else(|e| e.exit()); if opts.flag_help { println!("{}", USAGE); } else if opts.flag_interactive { interactive_console(&opts); ...
main
identifier_name
lib.rs
#![feature(ptr_eq)] extern crate symbolic_polynomials; #[macro_use] extern crate error_chain; #[macro_use] extern crate slog; extern crate slog_term; pub mod primitives; pub mod errors; pub mod props; pub mod graph; pub mod ops; #[macro_use] pub mod api; pub mod derivative; pub mod utils; pub mod export; pub mod back...
h = layer(&h, 10, &mut params, "6")?; // Error let error = api::sum_all((&h - &y) * (&h - &y))? / api::dim1(&y)?; // Calculate gradients let grads = derivative::gradient(&error, &params)?; // Generate SGD updates g.get_mut().scope.push("updates".into()); let updates: Vec<(Expr, Expr)> = ...
{ // Make the graph let g = GraphWrapper::default(); // Learning rate let alpha = &f_param!(g, (), "alpha")?; // Dummy let beta = &f_var!(g, ()); // Input let mut x = f_var!(g, (784, "n"), "input"); // Targets let y = f_var!(g, (10, "n"), "target"); // Parameters let mut ...
identifier_body
lib.rs
#![feature(ptr_eq)] extern crate symbolic_polynomials; #[macro_use] extern crate error_chain; #[macro_use] extern crate slog; extern crate slog_term; pub mod primitives; pub mod errors; pub mod props; pub mod graph; pub mod ops; #[macro_use] pub mod api; pub mod derivative; pub mod utils; pub mod export; pub mod back...
g.get_mut().scope.push("updates".into()); let updates: Vec<(Expr, Expr)> = params.iter().zip(grads.iter()) .map(|(& ref p, ref g)| (p.clone(), p - alpha * g)).collect(); g.get_mut().scope.clear(); let f = GraphFunction::new_from_expr(&[x, y], &[error], fal...
let grads = derivative::gradient(&error, &params)?; // Generate SGD updates
random_line_split
lib.rs
#![feature(ptr_eq)] extern crate symbolic_polynomials; #[macro_use] extern crate error_chain; #[macro_use] extern crate slog; extern crate slog_term; pub mod primitives; pub mod errors; pub mod props; pub mod graph; pub mod ops; #[macro_use] pub mod api; pub mod derivative; pub mod utils; pub mod export; pub mod back...
(x: &Expr, num_units: usize, params: &mut Vec<Expr>, prefix: &str) -> errors::Result<Expr> { let g = x.wrapper.clone(); let d: usize = x.get()?.shape.0.eval(&HashMap::new()).unwrap() as usize; let w = f_param!(g, (num_units, d), format!("{}::w", prefix))?; let b = f_param!(g, (num_units), format!("{}::b...
layer
identifier_name
catch_unwind.rs
use core::any::Any; use core::pin::Pin; use std::panic::{catch_unwind, AssertUnwindSafe, UnwindSafe}; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use pin_project_lite::pin_project; pin_project! { /// Future for the [`catch_unwind`](super::FutureExt::catch_unwind) method. #[deriv...
(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let f = self.project().future; catch_unwind(AssertUnwindSafe(|| f.poll(cx)))?.map(Ok) } }
poll
identifier_name
catch_unwind.rs
use core::any::Any; use core::pin::Pin; use std::panic::{catch_unwind, AssertUnwindSafe, UnwindSafe}; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use pin_project_lite::pin_project; pin_project! { /// Future for the [`catch_unwind`](super::FutureExt::catch_unwind) method. #[deriv...
} }
type Output = Result<Fut::Output, Box<dyn Any + Send>>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let f = self.project().future; catch_unwind(AssertUnwindSafe(|| f.poll(cx)))?.map(Ok)
random_line_split
catch_unwind.rs
use core::any::Any; use core::pin::Pin; use std::panic::{catch_unwind, AssertUnwindSafe, UnwindSafe}; use futures_core::future::Future; use futures_core::task::{Context, Poll}; use pin_project_lite::pin_project; pin_project! { /// Future for the [`catch_unwind`](super::FutureExt::catch_unwind) method. #[deriv...
}
{ let f = self.project().future; catch_unwind(AssertUnwindSafe(|| f.poll(cx)))?.map(Ok) }
identifier_body
mod.rs
pub use self::arch::{netent}; pub use self::arch::{hostent}; pub use self::arch::{servent}; pub use self::arch::{protoent}; pub use self::arch::{addrinfo}; pub use self::arch::{IPPORT_RESERVED}; pub use self::arch::{AI_PASSIVE}; pub use self::arch::{AI_CANONNAME}; pub use self::arch::{AI_NUMERICHOST}; pub use self::arc...
pub use self::arch::{EAI_AGAIN}; pub use self::arch::{EAI_BADFLAGS}; pub use self::arch::{EAI_FAIL}; pub use self::arch::{EAI_FAMILY}; pub use self::arch::{EAI_MEMORY}; pub use self::arch::{EAI_NONAME}; pub use self::arch::{EAI_SERVICE}; pub use self::arch::{EAI_SOCKTYPE}; pub use self::arch::{EAI_SYSTEM}; pub use self...
pub use self::arch::{NI_NOFQDN}; pub use self::arch::{NI_NUMERICHOST}; pub use self::arch::{NI_NAMEREQD}; pub use self::arch::{NI_NUMERICSERV}; pub use self::arch::{NI_DGRAM};
random_line_split
liveness-return-last-stmt-semi.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 ...
fn baz(x: u64) -> u32 { //~ ERROR not all control paths return a value x * 2; } fn main() { test!(); }
{ //~ ERROR not all control paths return a value x * 2; //~ NOTE consider removing this semicolon }
identifier_body
liveness-return-last-stmt-semi.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 ...
} fn main() { test!(); }
x * 2; //~ NOTE consider removing this semicolon } fn baz(x: u64) -> u32 { //~ ERROR not all control paths return a value x * 2;
random_line_split
liveness-return-last-stmt-semi.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 ...
() { test!(); }
main
identifier_name
macros.rs
// Copyright 2021 The Grin Developers // // 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 agree...
impl PartialOrd for $thing { #[inline] fn partial_cmp(&self, other: &$thing) -> Option<::std::cmp::Ordering> { Some(self.cmp(&other)) } } impl Ord for $thing { #[inline] fn cmp(&self, other: &$thing) -> ::std::cmp::Ordering { // manually implement comparison to get little-endian ordering ...
} } impl Eq for $thing {}
random_line_split
devtools.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 devtools_traits::{AutoMargins, CachedConsoleMessage, CachedConsoleMessageTypes}; use devtools_traits::{Compute...
pub fn handle_request_animation_frame(documents: &Documents, id: PipelineId, actor_name: String) { if let Some(doc) = documents.find_document(id) { doc.request_animation_frame(AnimationFrameCallback::DevtoolsFramerateTick { actor_...
{ if let Some(window) = documents.find_window(pipeline) { window.drop_devtools_timeline_markers(marker_types); } }
identifier_body
devtools.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 devtools_traits::{AutoMargins, CachedConsoleMessage, CachedConsoleMessageTypes}; use devtools_traits::{Compute...
} pub fn handle_reload(documents: &Documents, id: PipelineId) { if let Some(win) = documents.find_window(id) { win.Location().reload_without_origin_check(); } }
id: PipelineId, actor_name: String) { if let Some(doc) = documents.find_document(id) { doc.request_animation_frame(AnimationFrameCallback::DevtoolsFramerateTick { actor_name }); }
random_line_split
devtools.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 devtools_traits::{AutoMargins, CachedConsoleMessage, CachedConsoleMessageTypes}; use devtools_traits::{Compute...
(documents: &Documents, pipeline: PipelineId, reply: IpcSender<Option<NodeInfo>>) { let info = documents.find_document(pipeline) .map(|document| document.upcast::<Node>().summarize()); reply.send(info).unwrap(); } pub fn handle_get_document_element(documents: &Documents, ...
handle_get_root_node
identifier_name
specified_value_info.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/. */ //! Value information for devtools. use servo_arc::Arc; use std::ops::Range; use std::sync::Arc as StdArc; /// T...
(f: KeywordsCollectFn) { T::collect_completion_keywords(f); } } macro_rules! impl_generic_specified_value_info { ($ty:ident<$param:ident>) => { impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> { const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES; fn c...
collect_completion_keywords
identifier_name
specified_value_info.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/. */ //! Value information for devtools. use servo_arc::Arc; use std::ops::Range; use std::sync::Arc as StdArc; /// T...
const SUPPORTED_TYPES: u8 = $param::SUPPORTED_TYPES; fn collect_completion_keywords(f: KeywordsCollectFn) { $param::collect_completion_keywords(f); } } } } impl_generic_specified_value_info!(Option<T>); impl_generic_specified_value_info!(Vec<T>); impl_gene...
macro_rules! impl_generic_specified_value_info { ($ty:ident<$param:ident>) => { impl<$param: SpecifiedValueInfo> SpecifiedValueInfo for $ty<$param> {
random_line_split
specified_value_info.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/. */ //! Value information for devtools. use servo_arc::Arc; use std::ops::Range; use std::sync::Arc as StdArc; /// T...
}
{ T1::collect_completion_keywords(f); T2::collect_completion_keywords(f); }
identifier_body
unwind_safe.rs
use crate::cell::UnsafeCell; use crate::fmt; use crate::future::Future; use crate::ops::{Deref, DerefMut}; use crate::pin::Pin; use crate::ptr::{NonNull, Unique}; use crate::stream::Stream; use crate::task::{Context, Poll}; /// A marker trait which represents "panic safe" types in Rust. /// /// This trait is implement...
/// /// ## When should `UnwindSafe` be used? /// /// It is not intended that most types or functions need to worry about this trait. /// It is only used as a bound on the `catch_unwind` function and as mentioned /// above, the lack of `unsafe` means it is mostly an advisory. The /// [`AssertUnwindSafe`] wrapper struct ...
/// simply accessed as usual. /// /// Types like `&Mutex<T>`, however, are unwind safe because they implement /// poisoning by default. They still allow witnessing a broken invariant, but /// they already provide their own "speed bumps" to do so.
random_line_split
unwind_safe.rs
use crate::cell::UnsafeCell; use crate::fmt; use crate::future::Future; use crate::ops::{Deref, DerefMut}; use crate::pin::Pin; use crate::ptr::{NonNull, Unique}; use crate::stream::Stream; use crate::task::{Context, Poll}; /// A marker trait which represents "panic safe" types in Rust. /// /// This trait is implement...
(&self) -> &T { &self.0 } } #[stable(feature = "catch_unwind", since = "1.9.0")] impl<T> DerefMut for AssertUnwindSafe<T> { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } #[stable(feature = "catch_unwind", since = "1.9.0")] impl<R, F: FnOnce() -> R> FnOnce<()> for AssertUnwindSafe<F> ...
deref
identifier_name
unwind_safe.rs
use crate::cell::UnsafeCell; use crate::fmt; use crate::future::Future; use crate::ops::{Deref, DerefMut}; use crate::pin::Pin; use crate::ptr::{NonNull, Unique}; use crate::stream::Stream; use crate::task::{Context, Poll}; /// A marker trait which represents "panic safe" types in Rust. /// /// This trait is implement...
}
{ self.0.size_hint() }
identifier_body
upnp_listener.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/. */ //! UPnP listener for IP camera. //! extern crate url; use std::sync::Arc; use foxbox_taxonomy::manager::*; us...
use upnp::{UpnpListener, UpnpService}; pub struct IpCameraUpnpListener { manager: Arc<AdapterManager>, services: IpCameraServiceMap, config: Arc<ConfigService>, } impl IpCameraUpnpListener { pub fn new(manager: &Arc<AdapterManager>, services: IpCameraServiceMap, config: &Arc<ConfigService>) -> Box<Sel...
random_line_split
upnp_listener.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/. */ //! UPnP listener for IP camera. //! extern crate url; use std::sync::Arc; use foxbox_taxonomy::manager::*; us...
{ manager: Arc<AdapterManager>, services: IpCameraServiceMap, config: Arc<ConfigService>, } impl IpCameraUpnpListener { pub fn new(manager: &Arc<AdapterManager>, services: IpCameraServiceMap, config: &Arc<ConfigService>) -> Box<Self> { Box::new(IpCameraUpnpListener { manager: manag...
IpCameraUpnpListener
identifier_name
upnp_listener.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/. */ //! UPnP listener for IP camera. //! extern crate url; use std::sync::Arc; use foxbox_taxonomy::manager::*; us...
let url = try_get!(service.description, "/root/device/presentationURL"); let mut udn = try_get!(service.description, "/root/device/UDN").clone(); // The UDN is typically of the for uuid:SOME-UID-HERE, but some devices // response with just a UUID. We strip off the uuid: prefix, if it ...
{ return false; }
conditional_block
lib.rs
#![feature(asm)] #![feature(box_syntax)] #![feature(test)] #![feature(async_closure)]
#[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] extern crate bifrost; extern crate bifrost_hasher; extern crate bifrost_plugins; #[allow(unused_imports)] #[macro_use] pub extern crate dovahkiin; #[macro_use] extern crate serde_derive; #[macro_use] extern crate bitflags; extern crate ...
extern crate static_assertions;
random_line_split
fps.rs
use sfml::system::vector2; use sfml::traits::Drawable; use sfml::graphics::{Font, Text, Color, RenderTarget}; use sfml::graphics; use time; pub struct Fps<'a> { delta: f64, last_time: f64, fps: Text<'a> } impl<'a> Fps<'a> { pub fn new(font: &'a Font) -> Fps<'a> { let mut txt = Text::...
self.last_time = time::precise_time_s(); } pub fn register_delta(&mut self) { self.delta = self.elapsed_seconds() } pub fn elapsed_seconds(&self) -> f64 { time::precise_time_s() - self.last_time } pub fn draw_registered(&mut self, rw: &mut graphics::RenderWindow) { ...
pub fn reset(&mut self) {
random_line_split
fps.rs
use sfml::system::vector2; use sfml::traits::Drawable; use sfml::graphics::{Font, Text, Color, RenderTarget}; use sfml::graphics; use time; pub struct Fps<'a> { delta: f64, last_time: f64, fps: Text<'a> } impl<'a> Fps<'a> { pub fn new(font: &'a Font) -> Fps<'a>
pub fn reset(&mut self) { self.last_time = time::precise_time_s(); } pub fn register_delta(&mut self) { self.delta = self.elapsed_seconds() } pub fn elapsed_seconds(&self) -> f64 { time::precise_time_s() - self.last_time } pub fn draw_registered(&mut self, rw: &m...
{ let mut txt = Text::new().unwrap(); txt.set_font(font); txt.set_position(&vector2::Vector2f { x: 0.0, y: 0.0 }); txt.set_color(&Color::new_rgb(255, 255, 255)); Fps { delta: 0.0, last_time: 0.0, fps: txt } }
identifier_body
fps.rs
use sfml::system::vector2; use sfml::traits::Drawable; use sfml::graphics::{Font, Text, Color, RenderTarget}; use sfml::graphics; use time; pub struct Fps<'a> { delta: f64, last_time: f64, fps: Text<'a> } impl<'a> Fps<'a> { pub fn
(font: &'a Font) -> Fps<'a> { let mut txt = Text::new().unwrap(); txt.set_font(font); txt.set_position(&vector2::Vector2f { x: 0.0, y: 0.0 }); txt.set_color(&Color::new_rgb(255, 255, 255)); Fps { delta: 0.0, last_time: 0.0, fps: txt ...
new
identifier_name
query.rs
use serde_json::Value; // this modification was necessary because of this bug: // [https://github.com/rust-lang/rust/issues/63033](https://github.com/rust-lang/rust/issues/63033). // When the bug is resolved we can revert to the original Query from // commit: // [https://github.com/MindFlavor/AzureSDKForRust/commit/1b...
Param::new("p3", v3), ], ); let ser = serde_json::to_string(&query).unwrap(); assert_eq!( ser, r#"{"query":"SELECT * FROM t","parameters":[{"name":"p1","value":"string"},{"name":"p2","value":100},{"name":"p3","value":[1,2,3]}]}"# ); ...
p1.value("string"), Param::new("p2", 100u64),
random_line_split
query.rs
use serde_json::Value; // this modification was necessary because of this bug: // [https://github.com/rust-lang/rust/issues/63033](https://github.com/rust-lang/rust/issues/63033). // When the bug is resolved we can revert to the original Query from // commit: // [https://github.com/MindFlavor/AzureSDKForRust/commit/1b...
<'a> { query: &'a str, parameters: Vec<Param<'a>>, } #[derive(Debug, Serialize, Clone)] pub struct Param<'a> { name: &'a str, value: Value, } #[derive(Debug, Serialize, Clone)] pub struct ParamDef<'a> { name: &'a str, } impl<'a> Param<'a> { pub fn new<T: Into<Value>>(name: &'a str, value: T) ...
Query
identifier_name
query.rs
use serde_json::Value; // this modification was necessary because of this bug: // [https://github.com/rust-lang/rust/issues/63033](https://github.com/rust-lang/rust/issues/63033). // When the bug is resolved we can revert to the original Query from // commit: // [https://github.com/MindFlavor/AzureSDKForRust/commit/1b...
} impl<'a> ParamDef<'a> { pub fn new(name: &'a str) -> Self { Self { name } } pub fn value<T: Into<Value>>(&self, value: T) -> Param<'a> { Param { name: self.name, value: value.into(), } } //pub fn value_ref(&self, value: &'a Value) -> Param<'a> { ...
{ &self.value }
identifier_body
cfg-attr-syntax-validation.rs
#[cfg] //~ ERROR `cfg` is not followed by parentheses struct S1; #[cfg = 10] //~ ERROR `cfg` is not followed by parentheses struct S2; #[cfg()] //~ ERROR `cfg` predicate is not specified struct S3; #[cfg(a, b)] //~ ERROR multiple `cfg` predicates are specified struct S4; #[cfg("str")] //~ ERROR `cfg` predicate key ...
; #[cfg(a::b)] //~ ERROR `cfg` predicate key must be an identifier struct S6; #[cfg(a())] //~ ERROR invalid predicate `a` struct S7; #[cfg(a = 10)] //~ ERROR literal in `cfg` predicate value must be a string struct S8; #[cfg(a = b"hi")] //~ ERROR literal in `cfg` predicate value must be a string struct S9; macro_...
S5
identifier_name
cfg-attr-syntax-validation.rs
#[cfg] //~ ERROR `cfg` is not followed by parentheses struct S1; #[cfg = 10] //~ ERROR `cfg` is not followed by parentheses struct S2; #[cfg()] //~ ERROR `cfg` predicate is not specified struct S3; #[cfg(a, b)] //~ ERROR multiple `cfg` predicates are specified struct S4; #[cfg("str")] //~ ERROR `cfg` predicate key ...
#[cfg(a::b)] //~ ERROR `cfg` predicate key must be an identifier struct S6; #[cfg(a())] //~ ERROR invalid predicate `a` struct S7; #[cfg(a = 10)] //~ ERROR literal in `cfg` predicate value must be a string struct S8; #[cfg(a = b"hi")] //~ ERROR literal in `cfg` predicate value must be a string struct S9; macro_ru...
random_line_split
flag.rs
// use std::collections::HashSet; use std::fmt::{Display, Formatter, Result}; pub struct FlagBuilder<'n> { pub name: &'n str, /// The long version of the flag (i.e. word) /// without the preceding `--` pub long: Option<&'n str>, /// The string of text that will displayed to /// the user when th...
(&self, f: &mut Formatter) -> Result { if let Some(l) = self.long { write!(f, "--{}", l) } else { write!(f, "-{}", self.short.unwrap()) } } } #[cfg(test)] mod test { use super::FlagBuilder; #[test] fn flagbuilder_display() { ...
fmt
identifier_name
flag.rs
// use std::collections::HashSet; use std::fmt::{Display, Formatter, Result}; pub struct FlagBuilder<'n> { pub name: &'n str, /// The long version of the flag (i.e. word) /// without the preceding `--` pub long: Option<&'n str>, /// The string of text that will displayed to /// the user when th...
else { write!(f, "-{}", self.short.unwrap()) } } } #[cfg(test)] mod test { use super::FlagBuilder; #[test] fn flagbuilder_display() { let f = FlagBuilder { name: "flg", short: None, long: Some("flag"), help: None, ...
{ write!(f, "--{}", l) }
conditional_block
flag.rs
// use std::collections::HashSet; use std::fmt::{Display, Formatter, Result}; pub struct FlagBuilder<'n> { pub name: &'n str, /// The long version of the flag (i.e. word) /// without the preceding `--` pub long: Option<&'n str>, /// The string of text that will displayed to /// the user when th...
} #[cfg(test)] mod test { use super::FlagBuilder; #[test] fn flagbuilder_display() { let f = FlagBuilder { name: "flg", short: None, long: Some("flag"), help: None, multiple: true, blacklist: None, requires: None, ...
{ if let Some(l) = self.long { write!(f, "--{}", l) } else { write!(f, "-{}", self.short.unwrap()) } }
identifier_body
flag.rs
// use std::collections::HashSet; use std::fmt::{Display, Formatter, Result}; pub struct FlagBuilder<'n> { pub name: &'n str, /// The long version of the flag (i.e. word) /// without the preceding `--` pub long: Option<&'n str>, /// The string of text that will displayed to /// the user when th...
/// *may not* be used with this flag pub blacklist: Option<Vec<&'n str>>, /// A list of names of other arguments that /// are *required* to be used when this /// flag is used pub requires: Option<Vec<&'n str>>, /// The short version (i.e. single character) /// of the argument, no precedi...
/// I.e. `-v -v -v` or `-vvv` pub multiple: bool, /// A list of names for other arguments that
random_line_split
main.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 https://mozilla.org/MPL/2.0/. */ #![cfg(test)] #[macro_use] extern crate lazy_static; mod cookie; mod cookie_http_state; mod data_loader; mod fe...
.map_err(|_| ()) .and_then(move |ssl| { Http::new() .serve_connection( ssl, service_fn_ok(move |req: HyperRequest<Body>| { let mut response = HyperResponse::new(Vec::<u8>::new().into()); ...
{ let handler = Arc::new(handler); let listener = StdTcpListener::bind("[::0]:0").unwrap(); let listener = TcpListener::from_std(listener, &Handle::default()).unwrap(); let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); let url = ServoUrl::parse(&url_string).unwr...
identifier_body
main.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 https://mozilla.org/MPL/2.0/. */ #![cfg(test)] #[macro_use] extern crate lazy_static; mod cookie; mod cookie_http_state; mod data_loader; mod fe...
use embedder_traits::resources::{self, Resource}; use embedder_traits::{EmbedderProxy, EventLoopWaker}; use futures::{Future, Stream}; use hyper::server::conn::Http; use hyper::server::Server as HyperServer; use hyper::service::service_fn_ok; use hyper::{Body, Request as HyperRequest, Response as HyperResponse}; use ne...
random_line_split
main.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 https://mozilla.org/MPL/2.0/. */ #![cfg(test)] #[macro_use] extern crate lazy_static; mod cookie; mod cookie_http_state; mod data_loader; mod fe...
(&mut self, _: &Response) {} fn process_response_chunk(&mut self, _: Vec<u8>) {} /// Fired when the response is fully fetched fn process_response_eof(&mut self, response: &Response) { let _ = self.sender.send(response.clone()); } } fn fetch(request: &mut Request, dc: Option<Sender<DevtoolsContr...
process_response
identifier_name
writer.rs
use std::io::{self, Write}; use std::ptr; use super::ByteBuf; pub struct Writer<'a> { inner: &'a mut ByteBuf, } #[inline] pub(super) fn new<'a>(inner: &'a mut ByteBuf) -> Writer<'a> { Writer { inner } } impl<'a> Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mu...
else { unsafe { ptr::copy_nonoverlapping( src_dst, block.as_mut_ptr().offset(dst_off as isize), appendable, ); src_dst = src_dst.offset(appenda...
{ unsafe { ptr::copy_nonoverlapping( src_dst, block.as_mut_ptr().offset(dst_off as isize), n, ); } block.set_write_pos(dst_off +...
conditional_block
writer.rs
use std::io::{self, Write}; use std::ptr; use super::ByteBuf; pub struct Writer<'a> { inner: &'a mut ByteBuf, } #[inline] pub(super) fn new<'a>(inner: &'a mut ByteBuf) -> Writer<'a> { Writer { inner } } impl<'a> Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Result<usize>
src_dst, block.as_mut_ptr().offset(dst_off as isize), appendable, ); src_dst = src_dst.offset(appendable as isize); } n -= appendable; ...
{ let mut n = buf.len(); let mut src_dst = buf.as_ptr(); loop { if let Some(block) = self.inner.last_mut() { let dst_off = block.write_pos(); let appendable = block.appendable(); if appendable >= n { unsafe { ...
identifier_body
writer.rs
use std::io::{self, Write}; use std::ptr; use super::ByteBuf; pub struct Writer<'a> { inner: &'a mut ByteBuf, } #[inline] pub(super) fn new<'a>(inner: &'a mut ByteBuf) -> Writer<'a> { Writer { inner } } impl<'a> Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mu...
ptr::copy_nonoverlapping( src_dst, block.as_mut_ptr().offset(dst_off as isize), appendable, ); src_dst = src_dst.offset(appendable as isize); } ...
unsafe {
random_line_split
writer.rs
use std::io::{self, Write}; use std::ptr; use super::ByteBuf; pub struct Writer<'a> { inner: &'a mut ByteBuf, } #[inline] pub(super) fn
<'a>(inner: &'a mut ByteBuf) -> Writer<'a> { Writer { inner } } impl<'a> Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let mut n = buf.len(); let mut src_dst = buf.as_ptr(); loop { if let Some(block) = self.inner.last_mut() { l...
new
identifier_name
stack.rs
pub struct Stack<T> { elements: Vec<T> } impl<T> Stack<T> { pub fn new() -> Stack<T> { Stack { elements: Vec::new() } } pub fn push(&mut self, elem: T) { self.elements.push(elem); } pub fn pop(&mut self) -> T { let last = self.elements.len() - 1; ...
(&mut self) -> &mut T { let last = self.elements.len() - 1; &mut self.elements[last] } pub fn len(&self) -> usize { self.elements.len() } pub fn is_empty(&self) -> bool { self.elements.is_empty() } } fn main() { let mut stack = Stack::<i32>::new(); stack.pu...
peek_mut
identifier_name
stack.rs
pub struct Stack<T> { elements: Vec<T> } impl<T> Stack<T> { pub fn new() -> Stack<T> { Stack {
self.elements.push(elem); } pub fn pop(&mut self) -> T { let last = self.elements.len() - 1; self.elements.remove(last) } pub fn peek(&mut self) -> &T { let last = self.elements.len() - 1; &self.elements[last] } pub fn peek_mut(&mut self) -> &mut T { ...
elements: Vec::new() } } pub fn push(&mut self, elem: T) {
random_line_split
stack.rs
pub struct Stack<T> { elements: Vec<T> } impl<T> Stack<T> { pub fn new() -> Stack<T>
pub fn push(&mut self, elem: T) { self.elements.push(elem); } pub fn pop(&mut self) -> T { let last = self.elements.len() - 1; self.elements.remove(last) } pub fn peek(&mut self) -> &T { let last = self.elements.len() - 1; &self.elements[last] } p...
{ Stack { elements: Vec::new() } }
identifier_body
methods.rs
pub fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache, target: Target, context: &FetchContext) { // Step 1. if request.window == Window::Client { // TODO: Set window to request's client object if...
pub fn is_simple_method(m: &Method) -> bool { match *m { Method::Get | Method::Head | Method::Post => true, _ => false } } fn is_null_body_status(status: &Option<StatusCode>) -> bool { match *status { Some(status) => match status { StatusCode::SwitchingProtocols | Stat...
{ if h.is::<ContentType>() { match h.value() { Some(&ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) | Some(&ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _))) | Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::FormData, _))) => true, ...
identifier_body
methods.rs
} pub fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache, target: Target, context: &FetchContext) { // Step 1. if request.window == Window::Client { // TODO: Set window to request's client object ...
false }; if (same_origin &&!cors_flag ) || current_url.scheme() == "data" || current_url.scheme() == "file" || current_url.scheme() == "about" || request.mode == RequestMode::Navigate { basic_fetch(request, cache, target, done_chan...
*origin == current_url.origin() } else {
random_line_split
methods.rs
pub fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache, target: Target, context: &FetchContext) { // Step 1. if request.window == Window::Client { // TODO: Set window to request's client object if...
(m: &Method) -> bool { match *m { Method::Get | Method::Head | Method::Post => true, _ => false } } fn is_null_body_status(status: &Option<StatusCode>) -> bool { match *status { Some(status) => match status { StatusCode::SwitchingProtocols | StatusCode::NoContent | ...
is_simple_method
identifier_name
bad_insert_cont.rs
/* Copyright 2013 10gen Inc. * * 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 writi...
() { // batch with bad documents with several fields; cont on err let client = @Client::new(); match client.connect(~"127.0.0.1", MONGO_DEFAULT_PORT) { Ok(_) => (), Err(e) => fail!("%s", e.to_str()), } let coll = @Collection::new(~"rust", ~"bad_insert_batch_cont", client); // c...
test_bad_insert_cont
identifier_name
bad_insert_cont.rs
/* Copyright 2013 10gen Inc. * * 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 writi...
let ins_doc = match ins_str.to_bson_t() { Embedded(bson) => *bson, _ => fail!("what happened"), }; ins_strs = ins_strs + ~[ins_str]; ins_docs = ins_docs + ~[ins_doc]; i = i + 1; } coll.insert_batch(ins_strs, Some(~[CONT_ON_ERR]), None,...
{ // batch with bad documents with several fields; cont on err let client = @Client::new(); match client.connect(~"127.0.0.1", MONGO_DEFAULT_PORT) { Ok(_) => (), Err(e) => fail!("%s", e.to_str()), } let coll = @Collection::new(~"rust", ~"bad_insert_batch_cont", client); // clea...
identifier_body
bad_insert_cont.rs
/* Copyright 2013 10gen Inc. * * 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 writi...
} if j < 14 { fail!("fewer docs returned (%d) than successfully inserted (14)", j); } } Err(e) => fail!("%s", e.to_str()), } coll.remove(Some(SpecNotation(~"{ \"a\":1 }")), None, None, None); match client.disconnect() { Ok(_) => (), Err(e) => fail!("...
assert!(*ret_doc == ins_docs[valid_inds[j]]); j = j + 1;
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/. */ pub mod dom_manipulation; pub mod file_reading; pub mod history_traversal; pub mod networking; pub mod performance...
fn queue<T: Task + Send +'static>(&self, msg: Box<T>, global: &GlobalScope) -> Result<(), ()> { self.queue_with_canceller(msg, &global.task_canceller()) } }
T: Send + Task + 'static;
random_line_split