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
c-style-enum.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-MI...
{ TheOnlyVariant } static SINGLE_VARIANT: SingleVariant = TheOnlyVariant; static mut AUTO_ONE: AutoDiscriminant = One; static mut AUTO_TWO: AutoDiscriminant = One; static mut AUTO_THREE: AutoDiscriminant = One; static mut MANUAL_ONE: ManualDiscriminant = OneHundred; static mut MANUAL_TWO: ManualDiscriminant = O...
SingleVariant
identifier_name
c-style-enum.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-MI...
} static SINGLE_VARIANT: SingleVariant = TheOnlyVariant; static mut AUTO_ONE: AutoDiscriminant = One; static mut AUTO_TWO: AutoDiscriminant = One; static mut AUTO_THREE: AutoDiscriminant = One; static mut MANUAL_ONE: ManualDiscriminant = OneHundred; static mut MANUAL_TWO: ManualDiscriminant = OneHundred; static mut ...
enum SingleVariant { TheOnlyVariant
random_line_split
cssmediarule.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 cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use dom::bindings...
self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self.mediarule.read_with(&guard).to_css_string(&guard).into() } } impl CSSMediaRuleMethods for CSSMediaRule { // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media fn Media(&self) -> Root<MediaList> { ...
t_css(&
identifier_name
cssmediarule.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 cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use dom::bindings...
impl CSSMediaRuleMethods for CSSMediaRule { // https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media fn Media(&self) -> Root<MediaList> { self.medialist() } }
let guard = self.cssconditionrule.shared_lock().read(); self.mediarule.read_with(&guard).to_css_string(&guard).into() } }
identifier_body
cssmediarule.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 cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods; use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; use dom::bindings::js::{MutNullableJS, Root}; use dom::bind...
random_line_split
ranges_iter.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use super::range::Range; #[derive(PartialEq, Eq, Clone, Debug)] pub enum IterStatus { /// All ranges are consumed. Drained, /// Last range is drained or this iteration is a fresh start so that caller should scan /// on a new range. ...
(&mut self) { self.in_range = false; } } #[cfg(test)] mod tests { use super::super::range::IntervalRange; use super::*; use std::sync::atomic; static RANGE_INDEX: atomic::AtomicU64 = atomic::AtomicU64::new(1); fn new_range() -> Range { use byteorder::{BigEndian, WriteBytesExt...
notify_drained
identifier_name
ranges_iter.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use super::range::Range; #[derive(PartialEq, Eq, Clone, Debug)] pub enum IterStatus { /// All ranges are consumed. Drained, /// Last range is drained or this iteration is a fresh start so that caller should scan /// on a new range. ...
}
random_line_split
ranges_iter.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use super::range::Range; #[derive(PartialEq, Eq, Clone, Debug)] pub enum IterStatus { /// All ranges are consumed. Drained, /// Last range is drained or this iteration is a fresh start so that caller should scan /// on a new range. ...
/// Continues iterating. #[inline] pub fn next(&mut self) -> IterStatus { if self.in_range { return IterStatus::Continue; } match self.iter.next() { None => IterStatus::Drained, Some(range) => { self.in_range = true; ...
{ Self { in_range: false, iter: user_key_ranges.into_iter(), } }
identifier_body
ranges_iter.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use super::range::Range; #[derive(PartialEq, Eq, Clone, Debug)] pub enum IterStatus { /// All ranges are consumed. Drained, /// Last range is drained or this iteration is a fresh start so that caller should scan /// on a new range. ...
match self.iter.next() { None => IterStatus::Drained, Some(range) => { self.in_range = true; IterStatus::NewRange(range) } } } /// Notifies that current range is drained. #[inline] pub fn notify_drained(&mut self) { ...
{ return IterStatus::Continue; }
conditional_block
logging.rs
extern crate cql_ffi; use std::slice; use cql_ffi::*; unsafe fn print_error(future: &mut CassFuture) { let message = future.error_message(); let message = slice::from_raw_parts(&message.data, message.length as usize); println!("Error: {:?}", message); } unsafe fn
() -> *mut CassCluster { let cluster = CassCluster::new(); cluster.set_contact_points(str2ref("127.0.0.1,127.0.0.2,127.0.0.3")); cluster } unsafe fn connect_session(session: &mut CassSession, cluster: &mut CassCluster) -> CassError { let future: CassFuture = &mut session.connect(cluster); future.wa...
create_cluster
identifier_name
logging.rs
extern crate cql_ffi; use std::slice; use cql_ffi::*; unsafe fn print_error(future: &mut CassFuture) { let message = future.error_message(); let message = slice::from_raw_parts(&message.data, message.length as usize); println!("Error: {:?}", message); } unsafe fn create_cluster() -> *mut CassCluster { ...
close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); cass_cluster_free(cluster); cass_session_free(session); /* This *MUST* be the last driver call */ cass_log_cleanup(); fclose(log_file); return 0; }
{ cass_cluster_free(cluster); cass_session_free(session); return -1; }
conditional_block
logging.rs
extern crate cql_ffi; use std::slice; use cql_ffi::*; unsafe fn print_error(future: &mut CassFuture) { let message = future.error_message(); let message = slice::from_raw_parts(&message.data, message.length as usize); println!("Error: {:?}", message); } unsafe fn create_cluster() -> *mut CassCluster { ...
//~ fn on_log(message:&CassLogMessage, data:data) { //~ println!("{}", //~ message.time_ms / 1000, //~ message->time_ms % 1000, //~ cass_log_level_string(message.severity), //~ message.file, message.line, message.function, //~ message.message); //~ } fn main() { //~ C...
{ let future: CassFuture = &mut session.connect(cluster); future.wait(); future }
identifier_body
logging.rs
extern crate cql_ffi; use std::slice; use cql_ffi::*; unsafe fn print_error(future: &mut CassFuture) { let message = future.error_message(); let message = slice::from_raw_parts(&message.data, message.length as usize); println!("Error: {:?}", message); } unsafe fn create_cluster() -> *mut CassCluster { ...
if (connect_session(session, cluster)!= CASS_OK) { cass_cluster_free(cluster); cass_session_free(session); return -1; } close_future = cass_session_close(session); cass_future_wait(close_future); cass_future_free(close_future); cass_cluster_free(cluster); cass_session...
/* Log configuration *MUST* be done before any other driver call */ cass_log_set_level(CASS_LOG_INFO); cass_log_set_callback(on_log, log_file); cluster = create_cluster(); session = cass_session_new();
random_line_split
addon.rs
// Copyright (c) 2014 by SiegeLord // // All rights reserved. Distributed under ZLib. For full terms see the file LICENSE. #![allow(non_upper_case_globals)] use std::cell::RefCell; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; use allegro::Core; use allegro_font_sys::*; static mut initialized: bool = f...
else { al_init_font_addon(); initialized = true; spawned_on_this_thread.with(|x| *x.borrow_mut() = true); Ok(FontAddon{ core_mutex: core.get_core_mutex(), no_send_marker: PhantomData }) } } } pub fn get_version() -> i32 { unsafe { al_get_allegro_font_version() as i32 } } pub ...
{ if spawned_on_this_thread.with(|x| *x.borrow()) { Err("The font addon has already been created in this task.".to_string()) } else { spawned_on_this_thread.with(|x| *x.borrow_mut() = true); Ok(FontAddon{ core_mutex: core.get_core_mutex(), no_send_marker: PhantomData }) } }
conditional_block
addon.rs
// Copyright (c) 2014 by SiegeLord // // All rights reserved. Distributed under ZLib. For full terms see the file LICENSE. #![allow(non_upper_case_globals)] use std::cell::RefCell; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; use allegro::Core; use allegro_font_sys::*; static mut initialized: bool = f...
}
random_line_split
addon.rs
// Copyright (c) 2014 by SiegeLord // // All rights reserved. Distributed under ZLib. For full terms see the file LICENSE. #![allow(non_upper_case_globals)] use std::cell::RefCell; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; use allegro::Core; use allegro_font_sys::*; static mut initialized: bool = f...
{ core_mutex: Arc<Mutex<()>>, no_send_marker: PhantomData<*mut u8>, } impl FontAddon { pub fn init(core: &Core) -> Result<FontAddon, String> { let mutex = core.get_core_mutex(); let _guard = mutex.lock(); unsafe { if initialized { if spawned_on_this_thread.with(|x| *x.borrow()) { Err("T...
FontAddon
identifier_name
addon.rs
// Copyright (c) 2014 by SiegeLord // // All rights reserved. Distributed under ZLib. For full terms see the file LICENSE. #![allow(non_upper_case_globals)] use std::cell::RefCell; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; use allegro::Core; use allegro_font_sys::*; static mut initialized: bool = f...
initialized = true; spawned_on_this_thread.with(|x| *x.borrow_mut() = true); Ok(FontAddon{ core_mutex: core.get_core_mutex(), no_send_marker: PhantomData }) } } } pub fn get_version() -> i32 { unsafe { al_get_allegro_font_version() as i32 } } pub fn get_core_mutex(&self) -> Arc<Mutex<(...
{ let mutex = core.get_core_mutex(); let _guard = mutex.lock(); unsafe { if initialized { if spawned_on_this_thread.with(|x| *x.borrow()) { Err("The font addon has already been created in this task.".to_string()) } else { spawned_on_this_thread.with(|x| *x.borrow_mut() = true...
identifier_body
backtrace.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 ...
val == 2 } #[cfg(test)] mod tests { use prelude::v1::*; use sys_common; macro_rules! t { ($a:expr, $b:expr) => ({ let mut m = Vec::new(); sys_common::backtrace::demangle(&mut m, $a).unwrap(); assert_eq!(String::from_utf8(m).unwrap(), $b); }) } #[test] fn demangle() ...
None => 1, }; ENABLED.store(val, Ordering::SeqCst);
random_line_split
backtrace.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 ...
#[cfg(test)] mod tests { use prelude::v1::*; use sys_common; macro_rules! t { ($a:expr, $b:expr) => ({ let mut m = Vec::new(); sys_common::backtrace::demangle(&mut m, $a).unwrap(); assert_eq!(String::from_utf8(m).unwrap(), $b); }) } #[test] fn demangle() { t!("...
{ static ENABLED: atomic::AtomicIsize = atomic::AtomicIsize::new(0); match ENABLED.load(Ordering::SeqCst) { 1 => return false, 2 => return true, _ => {} } let val = match env::var_os("RUST_BACKTRACE") { Some(..) => 2, None => 1, }; ENABLED.store(val, Orde...
identifier_body
backtrace.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 ...
() { t!("_ZN13test$u20$test4foobE", "test test::foob"); t!("_ZN12test$BP$test4foobE", "test*test::foob"); } #[test] fn demangle_windows() { t!("ZN4testE", "test"); t!("ZN13test$u20$test4foobE", "test test::foob"); t!("ZN12test$RF$test4foobE", "test&test::foob"); ...
demangle_many_dollars
identifier_name
day_04.rs
use std::rc::Rc; type Link<T> = Option<Rc<Node<T>>>; struct Node<T> { item: T, next: Link<T> } impl <T> Node<T> { fn new(item: T, next: Link<T>) -> Link<T> { Some(Rc::new(Node { item, next })) } } pub struct List<T> { head: Link<T> } impl<T> List<T> { pub fn head(&self) -> Option<&T...
} pub struct ListIter<'l, T> { node: Option<&'l Node<T>> } impl<'l, T> Iterator for ListIter<'l, T> { type Item = &'l T; fn next(&mut self) -> Option<Self::Item> { self.node.take().map(|node| { self.node = node.next.as_ref().map(|node| &**node); &node.item }) ...
{ ListIter { node: self.head.as_ref().map(|node| &**node)} }
identifier_body
day_04.rs
use std::rc::Rc; type Link<T> = Option<Rc<Node<T>>>; struct Node<T> { item: T, next: Link<T> } impl <T> Node<T> { fn new(item: T, next: Link<T>) -> Link<T> { Some(Rc::new(Node { item, next })) } } pub struct List<T> { head: Link<T> } impl<T> List<T> { pub fn head(&self) -> Option<&T...
} #[test] fn append_single_item() { let mut list = List::default(); list = list.append(1); assert_eq!(list.head(), Some(&1)); } #[test] fn append_many_items() { let list = List::default().append(1).append(2).append(3); assert_eq!(list.head(), Some(&3)...
fn empty_list_head() { let list: List<i32> = List::default(); assert_eq!(list.head(), None);
random_line_split
day_04.rs
use std::rc::Rc; type Link<T> = Option<Rc<Node<T>>>; struct Node<T> { item: T, next: Link<T> } impl <T> Node<T> { fn new(item: T, next: Link<T>) -> Link<T> { Some(Rc::new(Node { item, next })) } } pub struct List<T> { head: Link<T> } impl<T> List<T> { pub fn head(&self) -> Option<&T...
else { break; } } } } #[cfg(test)] mod tests { use super::*; #[test] fn empty_list_head() { let list: List<i32> = List::default(); assert_eq!(list.head(), None); } #[test] fn append_single_item() { let mut list = List::default(...
{ link = node.next.take(); }
conditional_block
day_04.rs
use std::rc::Rc; type Link<T> = Option<Rc<Node<T>>>; struct Node<T> { item: T, next: Link<T> } impl <T> Node<T> { fn new(item: T, next: Link<T>) -> Link<T> { Some(Rc::new(Node { item, next })) } } pub struct List<T> { head: Link<T> } impl<T> List<T> { pub fn head(&self) -> Option<&T...
(&mut self) { let mut link = self.head.take(); while let Some(node) = link { if let Ok(mut node) = Rc::try_unwrap(node) { link = node.next.take(); } else { break; } } } } #[cfg(test)] mod tests { use super::*; #[t...
drop
identifier_name
issue-20616-2.rs
// We need all these 9 issue-20616-N.rs files // because we can only catch one parsing error at a time type Type_1_<'a, T> = &'a T; //type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T` type Type_2 = Type_1_<'static ()>; //~ error: expected one of `,`, `:`, `=`, or `>`, found ...
//type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,` //type Type_6 = Type_5_<'a,,>; // error: expected type, found `,` //type Type_7 = Box<(),,>; // error: expected type, found `,` //type Type_8<'a,,> = &'a (); // error: expected ident, found `,` //type Type_9<T,,> = Box<T>; // error: expe...
type Type_5_<'a> = Type_1_<'a, ()>;
random_line_split
unicode.rs
#[warn(clippy::invisible_characters)] fn zero() { print!("Here >​< is a ZWS, and ​another"); print!("This\u{200B}is\u{200B}fine"); print!("Here >­< is a SHY, and ­another"); print!("This\u{ad}is\u{ad}fine"); print!("Here >⁠< is a WJ, and ⁠another"); print!("This\u{2060}is\u{2060}fine"); } #[war...
zero(); uni(); canon(); }
("Üben!"); print!("\u{DC}ben!"); // this is ok } fn main() {
identifier_body
unicode.rs
#[warn(clippy::invisible_characters)] fn zero() {
print!("Here >​< is a ZWS, and ​another"); print!("This\u{200B}is\u{200B}fine"); print!("Here >­< is a SHY, and ­another"); print!("This\u{ad}is\u{ad}fine"); print!("Here >⁠< is a WJ, and ⁠another"); print!("This\u{2060}is\u{2060}fine"); } #[warn(clippy::unicode_not_nfc)] fn canon() { print...
random_line_split
unicode.rs
#[warn(clippy::invisible_characters)] fn zero() { print!("Here >​< is a ZWS, and ​another"); print!("This\u{200B}is\u{200B}fine"); print!("Here >­< is a SHY, and ­another"); print!("This\u{ad}is\u{ad}fine"); print!("Here >⁠< is a WJ, and ⁠another"); print!("This\u{2060}is\u{2060}fine"); } #[war...
(); uni(); canon(); }
zero
identifier_name
snippets.rs
use crate::ast::with_error_checking_parse; use crate::core::{Match, Session}; use crate::typeinf::get_function_declaration; use rustc_ast::ast::AssocItemKind; use rustc_parse::parser::ForceCollect; /// Returns completion snippets usable by some editors /// /// Generates a snippet string given a `Match`. The provided ...
} }) .collect(), }); } } debug!("Unable to parse method declaration. |{}|", source); None }) } ///Returns completion snippets usable by some ed...
{ if let AssocItemKind::Fn(ref fn_kind) = method.kind { let decl = &fn_kind.sig.decl; return Some(MethodInfo { // ident.as_str calls Ident.name.as_str name: method.ident.name.to_string(), args...
conditional_block
snippets.rs
use crate::ast::with_error_checking_parse; use crate::core::{Match, Session}; use crate::typeinf::get_function_declaration; use rustc_ast::ast::AssocItemKind; use rustc_parse::parser::ForceCollect; /// Returns completion snippets usable by some editors /// /// Generates a snippet string given a `Match`. The provided ...
Ok(name) => name, _ => "".into(), }; match source_map.span_to_snippet(arg.ty.span) { Ok(ref type_name) if!type_name.is_empty() => { ...
.inputs .iter() .map(|arg| { let source_map = &p.sess.source_map(); let var_name = match source_map.span_to_snippet(arg.pat.span) {
random_line_split
snippets.rs
use crate::ast::with_error_checking_parse; use crate::core::{Match, Session}; use crate::typeinf::get_function_declaration; use rustc_ast::ast::AssocItemKind; use rustc_parse::parser::ForceCollect; /// Returns completion snippets usable by some editors /// /// Generates a snippet string given a `Match`. The provided ...
}; match source_map.span_to_snippet(arg.ty.span) { Ok(ref type_name) if!type_name.is_empty() => { format!("{}: {}", var_name, type_name) } ...
{ let trim: &[_] = &['\n', '\r', '{', ' ']; let decorated = format!("{} {{}}()", source.trim_end_matches(trim)); trace!("MethodInfo::from_source_str: {:?}", decorated); with_error_checking_parse(decorated, |p| { if let Ok(Some(Some(method))) = p.parse_impl_item(ForceCollect:...
identifier_body
snippets.rs
use crate::ast::with_error_checking_parse; use crate::core::{Match, Session}; use crate::typeinf::get_function_declaration; use rustc_ast::ast::AssocItemKind; use rustc_parse::parser::ForceCollect; /// Returns completion snippets usable by some editors /// /// Generates a snippet string given a `Match`. The provided ...
() { let info = MethodInfo::from_source_str("pub fn new() -> Vec<T>").unwrap(); assert_eq!(info.name, "new"); assert_eq!(info.args.len(), 0); assert_eq!(info.snippet(), "new()"); let info = MethodInfo::from_source_str("pub fn reserve(&mut self, additional: usize)").unwrap(); assert_eq!(info.nam...
method_info_test
identifier_name
file_loader.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 mime_classifier::MIMEClassifier; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::{LoadData, Meta...
let progress_chan = start_sending_sniffed(senders, metadata, classifier, &buf); progress_chan.send(Payload(buf)).unwrap(); (read_all(reader, &progress...
let (res, progress_chan) = match res { Ok(ReadStatus::Partial(buf)) => {
random_line_split
file_loader.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 mime_classifier::MIMEClassifier; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::{LoadData, Meta...
(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MIMEClassifier>) { let url = load_data.url; assert!(&*url.scheme == "file"); spawn_named("file_loader".to_owned(), move || { let metadata = Metadata::default(url.clone()); let file_path: Result<PathBuf, ()> = url.to_file_path(); ...
factory
identifier_name
file_loader.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 mime_classifier::MIMEClassifier; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::{LoadData, Meta...
Ok(ReadStatus::EOF) | Err(_) => (res.map(|_| ()), start_sending(senders, metadata)), }; progress_chan.send(Done(res)).unwrap(); } Err(e) => { let p...
{ let progress_chan = start_sending_sniffed(senders, metadata, classifier, &buf); progress_chan.send(Payload(buf)).unwrap(); (read_all(reader, &progre...
conditional_block
file_loader.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 mime_classifier::MIMEClassifier; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::{LoadData, Meta...
}; progress_chan.send(Done(res)).unwrap(); } Err(e) => { let progress_chan = start_sending(senders, metadata); progress_chan.send(Done(Err(e.description().to_string()))).unwrap(); ...
{ let url = load_data.url; assert!(&*url.scheme == "file"); spawn_named("file_loader".to_owned(), move || { let metadata = Metadata::default(url.clone()); let file_path: Result<PathBuf, ()> = url.to_file_path(); match file_path { Ok(file_path) => { match F...
identifier_body
tests.rs
#![deny(warnings)] #![allow(unstable)] extern crate cargo; extern crate flate2; extern crate git2; extern crate hamcrest; extern crate serialize; extern crate tar; extern crate term; extern crate url; #[macro_use] extern crate log; mod support; macro_rules! test { ($name:ident $expr:expr) => ( #[test] ...
mod test_cargo_search; mod test_cargo_test; mod test_cargo_version; mod test_shell;
mod test_cargo_publish; mod test_cargo_registry; mod test_cargo_run;
random_line_split
parviewer.rs
/*! # ParView */ #![deny(non_camel_case_types)] #![deny(unused_parens)] #![deny(non_upper_case_globals)] #![deny(unused_qualifications)] #![deny(missing_docs)] #![deny(unused_results)] extern crate docopt; extern crate parview; extern crate serde; use docopt::Docopt; use serde::Deserialize; use std::error::Error; us...
let (frames, palette): (Vec<Frame>, Palette) = if args.flag_generate { let frames = misc::generate_frame(path)?; let palette = match args.flag_palette { None => Default::default(), Some(fname) => { let palette_path: &Path = Path::new(&fname[..]); ...
{ let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let toml_config: TomlConfig = match args.flag_config { None => Default::default(), Some(ref fname) => { let path: &Path = Path::new(&fname[..]); misc::load_...
identifier_body
parviewer.rs
/*! # ParView */ #![deny(non_camel_case_types)] #![deny(unused_parens)] #![deny(non_upper_case_globals)] #![deny(unused_qualifications)] #![deny(missing_docs)] #![deny(unused_results)] extern crate docopt; extern crate parview; extern crate serde; use docopt::Docopt; use serde::Deserialize; use std::error::Error; us...
None => "test_frame.json", }; let path: &Path = Path::new(fname); let (frames, palette): (Vec<Frame>, Palette) = if args.flag_generate { let frames = misc::generate_frame(path)?; let palette = match args.flag_palette { None => Default::default(), Some(fname) ...
let fname: &str = match args.arg_file { Some(ref s) => s,
random_line_split
parviewer.rs
/*! # ParView */ #![deny(non_camel_case_types)] #![deny(unused_parens)] #![deny(non_upper_case_globals)] #![deny(unused_qualifications)] #![deny(missing_docs)] #![deny(unused_results)] extern crate docopt; extern crate parview; extern crate serde; use docopt::Docopt; use serde::Deserialize; use std::error::Error; us...
() -> Result<(), Box<dyn Error>> { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let toml_config: TomlConfig = match args.flag_config { None => Default::default(), Some(ref fname) => { let path: &Path = Path::new(&fnam...
run
identifier_name
tac.rs
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "tac"; #[test] fn test_stdin_default() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.run_piped_stdin("100\n200\n300\n400\n500"); assert_eq!(result.stdout, "500400\n300\n200\n100\n"); } #[test] fn test_stdin_non_...
let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-s", ":", "delimited_primes.txt"]).run(); assert_eq!(result.stdout, at.read("delimited_primes.expected")); } #[test] fn test_single_non_newline_separator_before() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["...
random_line_split
tac.rs
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "tac"; #[test] fn test_stdin_default() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.run_piped_stdin("100\n200\n300\n400\n500"); assert_eq!(result.stdout, "500400\n300\n200\n100\n"); } #[test] fn test_stdin_non_...
#[test] fn test_single_default() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.arg("prime_per_line.txt").run(); assert_eq!(result.stdout, at.read("prime_per_line.expected")); } #[test] fn test_single_non_newline_separator() { let (at, mut ucmd) = testing(UTIL_NAME); let result = uc...
{ let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-b", "-s", ":"]).run_piped_stdin("100:200:300:400:500"); assert_eq!(result.stdout, "500:400:300:200:100"); }
identifier_body
tac.rs
#[macro_use] mod common; use common::util::*; static UTIL_NAME: &'static str = "tac"; #[test] fn test_stdin_default() { let (_, mut ucmd) = testing(UTIL_NAME); let result = ucmd.run_piped_stdin("100\n200\n300\n400\n500"); assert_eq!(result.stdout, "500400\n300\n200\n100\n"); } #[test] fn test_stdin_non_...
() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.args(&["-s", ":", "delimited_primes.txt"]).run(); assert_eq!(result.stdout, at.read("delimited_primes.expected")); } #[test] fn test_single_non_newline_separator_before() { let (at, mut ucmd) = testing(UTIL_NAME); let result = ucmd.arg...
test_single_non_newline_separator
identifier_name
issue-28871.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
type T = S; } trait T2 { type T: Iterator<Item=<S as T>::T>; } fn main() { }
random_line_split
issue-28871.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { }
main
identifier_name
lib.rs
#![recursion_limit = "1024"] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate chrono; extern crate crypto; extern crate env_logger; extern crate hex; extern crate migrant_lib; extern crate postgres; extern crate r2d2; extern crate r2d2_postgres; extern crate ring; extern crate ron; ex...
() -> Result<std::path::PathBuf> { Ok(std::env::var("CONFIG_DIR") .map(std::path::PathBuf::from) .unwrap_or_else(|_| std::env::current_dir().expect("unable to get current_dir"))) }
config_dir
identifier_name
lib.rs
#![recursion_limit = "1024"]
extern crate chrono; extern crate crypto; extern crate env_logger; extern crate hex; extern crate migrant_lib; extern crate postgres; extern crate r2d2; extern crate r2d2_postgres; extern crate ring; extern crate ron; extern crate serde; extern crate uuid; #[macro_use] extern crate serde_derive; #[macro_use] extern cra...
#[macro_use] extern crate lazy_static; #[macro_use] extern crate log;
random_line_split
lib.rs
#![recursion_limit = "1024"] #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; extern crate chrono; extern crate crypto; extern crate env_logger; extern crate hex; extern crate migrant_lib; extern crate postgres; extern crate r2d2; extern crate r2d2_postgres; extern crate ring; extern crate ron; ex...
{ Ok(std::env::var("CONFIG_DIR") .map(std::path::PathBuf::from) .unwrap_or_else(|_| std::env::current_dir().expect("unable to get current_dir"))) }
identifier_body
signature.rs
//! Kernel-provided signatures. //! We expose a new submodule for each use case, so arguments //! can be typed correctly and given separate context. use crate::random; use spin::Once; use ed25519_dalek::Keypair; static KEYPAIR: Once<Keypair> = Once::new(); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct In...
.sign_prehashed(prehashed, Some(SIGNATURE_CONTEXT)) .expect("Signing failed") } pub fn verify(pid: u64, cap: u64, signature: &Signature) -> Result<(), InvalidSignature> { let mut prehashed: Sha512 = Sha512::new(); prehashed.update(&pid.to_le_bytes()); prehashed.upd...
prehashed.update(&pid.to_le_bytes()); prehashed.update(&cap.to_le_bytes()); get_keypair()
random_line_split
signature.rs
//! Kernel-provided signatures. //! We expose a new submodule for each use case, so arguments //! can be typed correctly and given separate context. use crate::random; use spin::Once; use ed25519_dalek::Keypair; static KEYPAIR: Once<Keypair> = Once::new(); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct In...
} #[cfg(test)] mod tests { use ed25519_dalek::Signature; use super::capability; #[test] fn test_signature() { let s = capability::sign(5, 10); println!("{:?}", s); capability::verify(5, 10, &s).expect("Verify"); assert!(capability::verify(6, 10, &s).is_err()); ...
{ let mut prehashed: Sha512 = Sha512::new(); prehashed.update(&pid.to_le_bytes()); prehashed.update(&cap.to_le_bytes()); get_keypair() .verify_prehashed(prehashed, Some(SIGNATURE_CONTEXT), signature) .map_err(|_| InvalidSignature) }
identifier_body
signature.rs
//! Kernel-provided signatures. //! We expose a new submodule for each use case, so arguments //! can be typed correctly and given separate context. use crate::random; use spin::Once; use ed25519_dalek::Keypair; static KEYPAIR: Once<Keypair> = Once::new(); #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct In...
() { let s = capability::sign(5, 10); println!("{:?}", s); capability::verify(5, 10, &s).expect("Verify"); assert!(capability::verify(6, 10, &s).is_err()); let mut bytes = s.to_bytes(); bytes[0] = bytes[0].wrapping_add(1); let s2 = Signature::new(bytes); ...
test_signature
identifier_name
main.rs
extern crate itertools; extern crate structopt; #[macro_use] extern crate structopt_derive; use itertools::Itertools; use structopt::StructOpt; use std::fs::File; use std::io::Read; fn part1(input: &str) -> u64 { input .lines() .map(|line| { let (min, max) = line.split_whitespace() ...
(input: &str) -> u64 { input .lines() .map(|line| { let values: Vec<_> = line.split_whitespace() .filter_map(|entry| entry.parse::<u64>().ok()) .collect(); let mut result = None; 'outer: for a in &values { for b in &valu...
part2
identifier_name
main.rs
extern crate itertools; extern crate structopt; #[macro_use] extern crate structopt_derive; use itertools::Itertools; use structopt::StructOpt; use std::fs::File; use std::io::Read; fn part1(input: &str) -> u64 { input .lines() .map(|line| { let (min, max) = line.split_whitespace() ...
input .lines() .map(|line| { let values: Vec<_> = line.split_whitespace() .filter_map(|entry| entry.parse::<u64>().ok()) .collect(); let mut result = None; 'outer: for a in &values { for b in &values { ...
} fn part2(input: &str) -> u64 {
random_line_split
main.rs
extern crate itertools; extern crate structopt; #[macro_use] extern crate structopt_derive; use itertools::Itertools; use structopt::StructOpt; use std::fs::File; use std::io::Read; fn part1(input: &str) -> u64 { input .lines() .map(|line| { let (min, max) = line.split_whitespace() ...
else { let mut file = File::open(&opt.input) .expect(&format!("file {} not found", opt.input)); file.read_to_string(&mut contents) .expect(&format!("could not read file {}", opt.input)); } println!("Part 1: {}", part1(&contents)); println!("Part 2: {}", part2(&contents...
{ std::io::stdin() .read_to_string(&mut contents) .expect("could not read stdin"); }
conditional_block
main.rs
extern crate itertools; extern crate structopt; #[macro_use] extern crate structopt_derive; use itertools::Itertools; use structopt::StructOpt; use std::fs::File; use std::io::Read; fn part1(input: &str) -> u64 { input .lines() .map(|line| { let (min, max) = line.split_whitespace() ...
#[derive(StructOpt, Debug)] #[structopt(name = "day02", about = "Advent of code 2017 day 02")] struct Opt { #[structopt(help = "Input file")] input: String, } #[cfg(test)] mod tests { use super::*; #[test] fn part1_test() { assert_eq!(part1("5 1 9 5\n7 5 3\n2 4 6 8"), 18) } #[test] ...
{ let opt = Opt::from_args(); let mut contents = String::new(); if opt.input == "-" { std::io::stdin() .read_to_string(&mut contents) .expect("could not read stdin"); } else { let mut file = File::open(&opt.input) .expect(&format!("file {} not found", ...
identifier_body
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::{mem, net}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::{AsRawFd, RawFd}; use ports::localhost; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); l...
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), 0).unwrap(); for cmsg in msg.cmsgs() { i...
{ use nix::sys::uio::IoVec; use nix::unistd::{pipe, read, write, close}; use nix::sys::socket::{socketpair, sendmsg, recvmsg, AddressFamily, SockType, SockFlag, ControlMessage, CmsgSpace, MSG_TRUNC, MSG_CTRUNC}; let (fd1, ...
identifier_body
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::{mem, net}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::{AsRawFd, RawFd}; use ports::localhost; #[test] pub fn test_inetv4_addr_to_sock_addr() { let actual: net::SocketAddr = FromStr::from_str("127.0.0.1:3000").unwrap(); l...
let actual = Path::new("/foo/bar"); let addr = UnixAddr::new(actual).unwrap(); let expect: &'static [i8] = 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 std::net::TcpList...
} #[test] pub fn test_path_to_sock_addr() {
random_line_split
test_socket.rs
use nix::sys::socket::{InetAddr, UnixAddr, getsockname}; use std::{mem, net}; use std::path::Path; use std::str::FromStr; use std::os::unix::io::{AsRawFd, RawFd}; use ports::localhost; #[test] pub fn
() { 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()); ...
test_inetv4_addr_to_sock_addr
identifier_name
softmax.rs
use activation::Activation; #[derive(Copy, Clone)] pub struct SoftMax; impl SoftMax { pub fn new() -> SoftMax { return SoftMax; } } impl Activation for SoftMax { /// Calculates the SoftMax of input `x` fn calc(&self, x: Vec<f64>) -> Vec<f64> { let max_x = x.iter() .cloned()...
() { let activation = SoftMax::new(); let result = activation.calc(vec![1f64, 5f64, 4f64]); let validate = vec![-0.011963105252f64, 0.751918768228f64, 0.260044337024f64]; for (i, r) in result.iter().enumerate() { assert_approx_eq!(r, validate[i]); } } #[test...
softmax_test
identifier_name
softmax.rs
use activation::Activation; #[derive(Copy, Clone)] pub struct SoftMax; impl SoftMax { pub fn new() -> SoftMax { return SoftMax; } } impl Activation for SoftMax { /// Calculates the SoftMax of input `x` fn calc(&self, x: Vec<f64>) -> Vec<f64> { let max_x = x.iter() .cloned()...
fn softmax_derivative_correctness_test() { let activation = SoftMax::new(); let delta = 1e-10f64; let val = vec![0.5f64, 0.1f64, 0.9f64]; let val_delta = val.iter().map(|n| n + delta).collect::<Vec<_>>(); let approx = activation .calc(val_delta) .iter()...
#[test] #[ignore]
random_line_split
softmax.rs
use activation::Activation; #[derive(Copy, Clone)] pub struct SoftMax; impl SoftMax { pub fn new() -> SoftMax { return SoftMax; } } impl Activation for SoftMax { /// Calculates the SoftMax of input `x` fn calc(&self, x: Vec<f64>) -> Vec<f64> { let max_x = x.iter() .cloned()...
}
{ let activation = SoftMax::new(); let delta = 1e-10f64; let val = vec![0.5f64, 0.1f64, 0.9f64]; let val_delta = val.iter().map(|n| n + delta).collect::<Vec<_>>(); let approx = activation .calc(val_delta) .iter() .zip(activation.calc(val.clone...
identifier_body
sequential.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/. */ //! Implements sequential traversal over the DOM tree. #![deny(missing_docs)] use context::TraversalStatistics; ...
let mut traversal_data = PerLevelTraversalData { current_dom_depth: None, }; let mut tlc = traversal.create_thread_local_context(); if token.traverse_unstyled_children_only() { for kid in root.as_node().children() { if kid.as_element().map_or(false, |el| el.get_data().is_n...
{ traversal.process_preorder(traversal_data, thread_local, node); if let Some(el) = node.as_element() { if let Some(ref mut depth) = traversal_data.current_dom_depth { *depth += 1; } traversal.traverse_children(thread_local, el, |tlc, kid| { ...
identifier_body
sequential.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/. */ //! Implements sequential traversal over the DOM tree. #![deny(missing_docs)] use context::TraversalStatistics; ...
<E, D>(traversal: &D, traversal_data: &mut PerLevelTraversalData, thread_local: &mut D::ThreadLocalContext, node: E::ConcreteNode) where E: TElement, D: DomTraversal<E> { traversal.process_preorder(traversal_data, thread_local, node); if let Some(el) = node.as...
doit
identifier_name
sequential.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/. */ //! Implements sequential traversal over the DOM tree. #![deny(missing_docs)] use context::TraversalStatistics; ...
}
{ println!("{}", tlsc.statistics); }
conditional_block
sequential.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/. */ //! Implements sequential traversal over the DOM tree. #![deny(missing_docs)] use context::TraversalStatistics; ...
let mut traversal_data = PerLevelTraversalData { current_dom_depth: None, }; let mut tlc = traversal.create_thread_local_context(); if token.traverse_unstyled_children_only() { for kid in root.as_node().children() { if kid.as_element().map_or(false, |el| el.get_data().is_non...
random_line_split
wbalance.rs
/* * Copyright (C) 2012 The Android Open Source Project * * 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 app...
int maximum = max(estimation.r, max(estimation.g, estimation.b)); float avg = (minimum + maximum) / 2.f; scale.r = avg / estimation.r; scale.g = avg / estimation.g; scale.b = avg / estimation.b; } uchar4 __attribute__((kernel)) whiteBalanceKernel(uchar4 in) { float3 t = convert_float3(in.rg...
void prepareWhiteBalance() { uchar4 estimation = estimateWhite(); int minimum = min(estimation.r, min(estimation.g, estimation.b));
random_line_split
without_loop_counters.rs
#![warn(clippy::needless_range_loop, clippy::manual_memcpy)] const LOOP_OFFSET: usize = 5000; pub fn manual_copy(src: &[i32], dst: &mut [i32], dst2: &mut [i32]) { // plain manual memcpy for i in 0..src.len() { dst[i] = src[i]; } // dst offset memcpy for i in 0..src.len() { dst[i +...
(src: &[String], dst: &mut [String]) { for i in 0..src.len() { dst[i] = src[i].clone(); } } fn main() {}
manual_clone
identifier_name
without_loop_counters.rs
#![warn(clippy::needless_range_loop, clippy::manual_memcpy)] const LOOP_OFFSET: usize = 5000; pub fn manual_copy(src: &[i32], dst: &mut [i32], dst2: &mut [i32]) { // plain manual memcpy for i in 0..src.len() { dst[i] = src[i]; } // dst offset memcpy for i in 0..src.len() { dst[i +...
} // multiple copies - suggest two memcpy statements for i in 10..256 { dst[i] = src[i - 5]; dst2[i + 500] = src[i] } // this is a reversal - the copy lint shouldn't be triggered for i in 10..LOOP_OFFSET { dst[i + LOOP_OFFSET] = src[LOOP_OFFSET - i]; } let som...
{ break; }
conditional_block
without_loop_counters.rs
#![warn(clippy::needless_range_loop, clippy::manual_memcpy)] const LOOP_OFFSET: usize = 5000; pub fn manual_copy(src: &[i32], dst: &mut [i32], dst2: &mut [i32]) { // plain manual memcpy for i in 0..src.len() { dst[i] = src[i]; } // dst offset memcpy for i in 0..src.len() { dst[i +...
dst[i] = src[i - 5]; dst2[i + 500] = src[i] } // this is a reversal - the copy lint shouldn't be triggered for i in 10..LOOP_OFFSET { dst[i + LOOP_OFFSET] = src[LOOP_OFFSET - i]; } let some_var = 5; // Offset in variable for i in 10..LOOP_OFFSET { dst[i + LO...
random_line_split
issue-2631-b.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 v = ~[@~"hi"]; let mut m: req::header_map = HashMap::new(); m.insert(~"METHOD", @RefCell::new(v)); request::<int>(&m); }
identifier_body
issue-2631-b.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 ...
use req::request; use std::cell::RefCell; use std::hashmap::HashMap; pub fn main() { let v = ~[@~"hi"]; let mut m: req::header_map = HashMap::new(); m.insert(~"METHOD", @RefCell::new(v)); request::<int>(&m); }
extern mod req;
random_line_split
issue-2631-b.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 v = ~[@~"hi"]; let mut m: req::header_map = HashMap::new(); m.insert(~"METHOD", @RefCell::new(v)); request::<int>(&m); }
main
identifier_name
stylepropertymapreadonly.rs
* 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::StylePropertyMapReadOnlyBinding::StylePropertyMapReadOnlyMethods; use dom::bindings::codegen::Bindings::StylePropertyMapReadOnlyBinding::Wrap; use ...
/* This Source Code Form is subject to the terms of the Mozilla Public
random_line_split
stylepropertymapreadonly.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::StylePropertyMapReadOnlyBinding::StylePropertyMapReadOnlyMethods; use dom::b...
{ reflector: Reflector, entries: HashMap<Atom, JS<CSSStyleValue>>, } impl StylePropertyMapReadOnly { fn new_inherited<Entries>(entries: Entries) -> StylePropertyMapReadOnly where Entries: IntoIterator<Item=(Atom, JS<CSSStyleValue>)> { StylePropertyMapReadOnly { reflector: R...
StylePropertyMapReadOnly
identifier_name
stylepropertymapreadonly.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::StylePropertyMapReadOnlyBinding::StylePropertyMapReadOnlyMethods; use dom::b...
}
{ // TODO: avoid constructing an Atom self.entries.contains_key(&Atom::from(property)) }
identifier_body
atomic_xor_relaxed.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_xor_relaxed; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_xor_relaxed<T>(dst: *mut T, src: T) -> T; struct
<T> { v: UnsafeCell<T> } unsafe impl Sync for A<T> {} impl<T> A<T> { fn new(v: T) -> A<T> { A { v: UnsafeCell::<T>::new(v) } } } type T = usize; macro_rules! atomic_xor_relaxed_test { ($init:expr, $value:expr, $result:expr) => ({ let value: T = $init; let a: A<T> = A::<T>:...
A
identifier_name
atomic_xor_relaxed.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::atomic_xor_relaxed; use core::cell::UnsafeCell; use std::sync::Arc; use std::thread; // pub fn atomic_xor_relaxed<T>(dst: *mut T, src: T) -> T; struct A<T> { v: UnsafeCell<T> } un...
#[test] fn atomic_xor_relaxed_test1() { atomic_xor_relaxed_test!( 0xff00, 0x0a0a, 0xf50a ); } }
}
random_line_split
bench.rs
#![feature(test)] extern crate fdlimit; extern crate test; extern crate tiny_http; use std::io::Write; use std::process::Command; use tiny_http::Method; #[test] #[ignore] // TODO: obtain time fn curl_bench() { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port();...
(bencher: &mut test::Bencher) { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port(); let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); bencher.iter(|| { (write!(stream, "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")).unwra...
sequential_requests
identifier_name
bench.rs
#![feature(test)] extern crate fdlimit; extern crate test; extern crate tiny_http; use std::io::Write; use std::process::Command; use tiny_http::Method; #[test] #[ignore] // TODO: obtain time fn curl_bench() { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port();...
let request = match server.try_recv().unwrap() { None => break, Some(rq) => rq, }; assert_eq!(request.method(), &Method::Get); request.respond(tiny_http::Response::new_empty(tiny_http::StatusCode(204))); } }); }
{ fdlimit::raise_fd_limit(); let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port(); bencher.iter(|| { let mut streams = Vec::new(); for _ in 0..1000usize { let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwra...
identifier_body
bench.rs
#![feature(test)] extern crate fdlimit; extern crate test; extern crate tiny_http; use std::io::Write; use std::process::Command; use tiny_http::Method; #[test] #[ignore] // TODO: obtain time fn curl_bench() { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port();...
#[bench] fn sequential_requests(bencher: &mut test::Bencher) { let server = tiny_http::Server::http("0.0.0.0:0").unwrap(); let port = server.server_addr().port(); let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); bencher.iter(|| { (write!(stream, "GET / HTTP/1.1\r\n...
Err(_) => return, // ignoring test }; drop(server); }
random_line_split
api.rs
use std::io::Cursor; use rustc_serialize::json; use rustc_serialize::json::Json; use tiny_http::{Response, StatusCode}; use http::{ok, okJson, http_response}; use table::Tables; use table::TableError; pub fn post_table(tables: &mut Tables, table: &str) -> Response<Cursor<Vec<u8>>> { println!("Creating Table: {...
} pub fn post_key_to_table(tables: &mut Tables, table: &str, key: &str, data: Json) -> Response<Cursor<Vec<u8>>> { match tables.put(table, key, data) { Err(e) => handle_table_error(e), Ok(_) => ok(format!("Successfully added key: {} to table {}", key, table)) } } pub fn get_key(tables: &mut Ta...
}
random_line_split
api.rs
use std::io::Cursor; use rustc_serialize::json; use rustc_serialize::json::Json; use tiny_http::{Response, StatusCode}; use http::{ok, okJson, http_response}; use table::Tables; use table::TableError; pub fn post_table(tables: &mut Tables, table: &str) -> Response<Cursor<Vec<u8>>> { println!("Creating Table: ...
fn handle_table_error(error: TableError) -> Response<Cursor<Vec<u8>>> { match error { TableError::TableDoesNotExist => http_response(StatusCode(400), "Table does not exist"), TableError::TableAlreadyExists => http_response(StatusCode(400), "Table already exists"), TableError::KeyAlreadyPr...
{ match tables.delete_table(table) { Err(e) => handle_table_error(e), Ok(_) => ok(format!("Successfully deleted table: {}", table)), } }
identifier_body
api.rs
use std::io::Cursor; use rustc_serialize::json; use rustc_serialize::json::Json; use tiny_http::{Response, StatusCode}; use http::{ok, okJson, http_response}; use table::Tables; use table::TableError; pub fn post_table(tables: &mut Tables, table: &str) -> Response<Cursor<Vec<u8>>> { println!("Creating Table: ...
(tables: &mut Tables, table: &str, key: &str) -> Response<Cursor<Vec<u8>>> { match tables.get(table, key) { Err(e) => handle_table_error(e), Ok(json) => okJson(json), } } pub fn delete_key_from_table(tables: &mut Tables, table: &str, key: &str) -> Response<Cursor<Vec<u8>>> { match tables.de...
get_key
identifier_name
db.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/. */ //! Stores subscription information for WebPush. //! //! # The WebPush database //! //! The "subscriptions" table ...
/// Removes an existing push subscription identified by `push_uri`. pub fn unsubscribe(&self, _: i32, push_uri: &str) -> rusqlite::Result<c_int> { self.db.execute("DELETE FROM subscriptions WHERE push_uri=$1", &[&escape(push_uri)] ) } /// Sets the resources to ...
{ self.db.execute("INSERT INTO subscriptions VALUES ($1, $2, $3)", &[&user_id, &escape(&sub.push_uri), &escape(&sub.public_key)] ) }
identifier_body
db.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/. */ //! Stores subscription information for WebPush. //! //! # The WebPush database //! //! The "subscriptions" table ...
public_key: "u1_sub0_pkey".to_owned() }).unwrap(); db.subscribe(1, &Subscription { push_uri: "u1_sub1_puri".to_owned(), public_key: "u1_sub1_pkey".to_owned() }).unwrap(); db.subscribe(2, &Subscription { push_uri: "u2_sub0_puri".to_owned(), ...
db.subscribe(1, &Subscription { push_uri: "u1_sub0_puri".to_owned(),
random_line_split
db.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/. */ //! Stores subscription information for WebPush. //! //! # The WebPush database //! //! The "subscriptions" table ...
(&self, _: i32, push_uri: &str) -> rusqlite::Result<c_int> { self.db.execute("DELETE FROM subscriptions WHERE push_uri=$1", &[&escape(push_uri)] ) } /// Sets the resources to subscribe to notifications for the user `user_id`. pub fn set_resources(&self, user_id: i32,...
unsubscribe
identifier_name
canvas_render_task.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 azure::azure_hl::{DrawTarget, Color, B8G8R8A8, SkiaBackend, StrokeOptions, DrawOptions}; use azure::azure_hl::...
} pub struct CanvasRenderTask { drawtarget: DrawTarget, fill_color: ColorPattern, stroke_color: ColorPattern, stroke_opts: StrokeOptions, } impl CanvasRenderTask { fn new(size: Size2D<i32>) -> CanvasRenderTask { CanvasRenderTask { drawtarget: CanvasRenderTask::create(size), ...
Close,
random_line_split
canvas_render_task.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 azure::azure_hl::{DrawTarget, Color, B8G8R8A8, SkiaBackend, StrokeOptions, DrawOptions}; use azure::azure_hl::...
{ drawtarget: DrawTarget, fill_color: ColorPattern, stroke_color: ColorPattern, stroke_opts: StrokeOptions, } impl CanvasRenderTask { fn new(size: Size2D<i32>) -> CanvasRenderTask { CanvasRenderTask { drawtarget: CanvasRenderTask::create(size), fill_color: ColorPatt...
CanvasRenderTask
identifier_name
canvas_render_task.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 azure::azure_hl::{DrawTarget, Color, B8G8R8A8, SkiaBackend, StrokeOptions, DrawOptions}; use azure::azure_hl::...
fn create(size: Size2D<i32>) -> DrawTarget { DrawTarget::new(SkiaBackend, size, B8G8R8A8) } fn recreate(&mut self, size: Size2D<i32>) { self.drawtarget = CanvasRenderTask::create(size); } }
{ let drawopts = DrawOptions::new(1.0, 0); self.drawtarget.stroke_rect(rect, &self.stroke_color, &self.stroke_opts, &drawopts); }
identifier_body
webglbuffer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
} } impl WebGLBuffer { pub fn id(&self) -> u32 { self.id } // NB: Only valid buffer targets come here pub fn bind(&self, target: u32) -> WebGLResult<()> { if let Some(previous_target) = self.target.get() { if target!= previous_target { return Err(WebGLE...
pub fn new(global: GlobalRef, renderer: IpcSender<CanvasMsg>, id: u32) -> Root<WebGLBuffer> { reflect_dom_object(box WebGLBuffer::new_inherited(renderer, id), global, WebGLBufferBinding::Wrap)
random_line_split
webglbuffer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
(global: GlobalRef, renderer: IpcSender<CanvasMsg>, id: u32) -> Root<WebGLBuffer> { reflect_dom_object(box WebGLBuffer::new_inherited(renderer, id), global, WebGLBufferBinding::Wrap) } } impl WebGLBuffer { pub fn id(&self) -> u32 { self.id } // NB: Only valid buffer targets come here ...
new
identifier_name
webglbuffer.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use canvas_traits::{CanvasMsg, CanvasWebGLMsg...
} else { self.target.set(Some(target)); } self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::BindBuffer(target, self.id))).unwrap(); Ok(()) } pub fn delete(&self) { if!self.is_deleted.get() { self.is_deleted.set(true); let _ = self....
{ return Err(WebGLError::InvalidOperation); }
conditional_block
service.rs
// Copyright 2015, 2016 Ethcore (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....
} IoMessage::RegisterStream { handler_id, token } => { let handler = self.handlers.get(handler_id).expect("Unknown handler id").clone(); handler.register_stream(token, Token(token + handler_id * TOKENS_PER_HANDLER), event_loop); } IoMessage::DeregisterStream { handler_id, token } => { let handl...
{ event_loop.clear_timeout(timer.timeout); }
conditional_block
service.rs
// Copyright 2015, 2016 Ethcore (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....
/// Regiter a IO hadnler with the event loop. pub fn register_handler(&mut self, handler: Arc<IoHandler<Message> + Send>) -> Result<(), IoError> { try!(self.host_channel.send(IoMessage::AddHandler { handler: handler })); Ok(()) } /// Send a message over the network. Normaly `HostIo::send` should be used. This...
host_channel: channel, }) }
random_line_split
service.rs
// Copyright 2015, 2016 Ethcore (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....
(channel: IoChannel<Message>, handler: HandlerId) -> IoContext<Message> { IoContext { handler: handler, channel: channel, } } /// Register a new IO timer. 'IoHandler::timeout' will be called with the token. pub fn register_timer(&self, token: TimerToken, ms: u64) -> Result<(), UtilError> { try!(self.cha...
new
identifier_name
pascals-triangle.rs
extern crate pascals_triangle; use pascals_triangle::*; #[test] fn no_rows() { let pt = PascalsTriangle::new(0); let expected: Vec<Vec<u32>> = Vec::new(); assert_eq!(expected, pt.rows()); } #[test] fn one_row() { let pt = PascalsTriangle::new(1); let expected: Vec<Vec<u32>> = vec![vec![1]]; a...
() { let pt = PascalsTriangle::new(2); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1]]; assert_eq!(expected, pt.rows()); } #[test] fn three_rows() { let pt = PascalsTriangle::new(3); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1], vec![1, 2, 1]]; assert_eq!(expected, pt.rows());...
two_rows
identifier_name
pascals-triangle.rs
extern crate pascals_triangle; use pascals_triangle::*; #[test] fn no_rows() { let pt = PascalsTriangle::new(0); let expected: Vec<Vec<u32>> = Vec::new(); assert_eq!(expected, pt.rows()); } #[test] fn one_row() { let pt = PascalsTriangle::new(1); let expected: Vec<Vec<u32>> = vec![vec![1]]; a...
#[test] fn three_rows() { let pt = PascalsTriangle::new(3); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1], vec![1, 2, 1]]; assert_eq!(expected, pt.rows()); } #[test] fn last_of_four_rows() { let pt = PascalsTriangle::new(4); let expected: Vec<u32> = vec![1, 3, 3, 1]; assert_eq!(expec...
{ let pt = PascalsTriangle::new(2); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1]]; assert_eq!(expected, pt.rows()); }
identifier_body
pascals-triangle.rs
extern crate pascals_triangle; use pascals_triangle::*;
assert_eq!(expected, pt.rows()); } #[test] fn one_row() { let pt = PascalsTriangle::new(1); let expected: Vec<Vec<u32>> = vec![vec![1]]; assert_eq!(expected, pt.rows()); } #[test] fn two_rows() { let pt = PascalsTriangle::new(2); let expected: Vec<Vec<u32>> = vec![vec![1], vec![1, 1]]; ass...
#[test] fn no_rows() { let pt = PascalsTriangle::new(0); let expected: Vec<Vec<u32>> = Vec::new();
random_line_split
issue-42467.rs
// Copyright 2017 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 ...
(&mut self) -> Option<()> { None } } impl<T> IntoIterator for Foo<T> { type Item = (); type IntoIter = IntoIter<T>; fn into_iter(self) -> IntoIter<T> { IntoIter(self.0) } } fn main() {}
next
identifier_name
issue-42467.rs
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(dead_code)] struct Foo<T>(T); struct IntoIter<T>(T); impl<'a,...
random_line_split