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
delete.rs
// Copyright (c) 2016-2018 Chef Software Inc. and/or applicable contributors // // 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 // // Unl...
{ let depot_client = DepotClient::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::DepotClient)?; ui.status(Status::Deleting, format!("secret {}.", key))?; depot_client .delete_origin_secret(origin, token, key) .map_err(Error::DepotClient)?; ui.status(Status::Deleted, form...
identifier_body
delete.rs
// Copyright (c) 2016-2018 Chef Software Inc. and/or applicable contributors // // 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 // // Unl...
(ui: &mut UI, bldr_url: &str, token: &str, origin: &str, key: &str) -> Result<()> { let depot_client = DepotClient::new(bldr_url, PRODUCT, VERSION, None).map_err(Error::DepotClient)?; ui.status(Status::Deleting, format!("secret {}.", key))?; depot_client .delete_origin_secret(origin, token,...
start
identifier_name
main.rs
#![crate_name = "weather-client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; fn atoi(s: &str) -> int { from_str(s).unwrap() } fn main() { println!("Collecting updates from weather server..."); ...
let mut total_temp = 0; for _ in range(0i, 100i) { let string = subscriber.recv_str(0).unwrap(); let chks: Vec<int> = string.as_slice().split(' ').map(|x| atoi(x)).collect(); let (_zipcode, temperature, _relhumidity) = (chks[0], chks[1], chks[2]); total_temp += temperature; ...
assert!(subscriber.connect("tcp://localhost:5556").is_ok()); let args = std::os::args(); let filter = if args.len() > 1 { args[1].clone() } else { "10001".to_string() }; assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok());
random_line_split
main.rs
#![crate_name = "weather-client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; fn
(s: &str) -> int { from_str(s).unwrap() } fn main() { println!("Collecting updates from weather server..."); let mut context = zmq::Context::new(); let mut subscriber = context.socket(zmq::SUB).unwrap(); assert!(subscriber.connect("tcp://localhost:5556").is_ok()); let args = std::os::args(); ...
atoi
identifier_name
main.rs
#![crate_name = "weather-client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; fn atoi(s: &str) -> int { from_str(s).unwrap() } fn main() { println!("Collecting updates from weather server..."); ...
; assert!(subscriber.set_subscribe(filter.as_bytes()).is_ok()); let mut total_temp = 0; for _ in range(0i, 100i) { let string = subscriber.recv_str(0).unwrap(); let chks: Vec<int> = string.as_slice().split(' ').map(|x| atoi(x)).collect(); let (_zipcode, temperature, _relhumidity) =...
{ "10001".to_string() }
conditional_block
main.rs
#![crate_name = "weather-client"] /*! * Weather update client * Connects SUB socket to tcp://localhost:5556 * Collects weather updates and find avg temp in zipcode */ extern crate zmq; fn atoi(s: &str) -> int
fn main() { println!("Collecting updates from weather server..."); let mut context = zmq::Context::new(); let mut subscriber = context.socket(zmq::SUB).unwrap(); assert!(subscriber.connect("tcp://localhost:5556").is_ok()); let args = std::os::args(); let filter = if args.len() > 1 { args[1]....
{ from_str(s).unwrap() }
identifier_body
bench.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use lz4_pyframe::compress; use lz4_pyframe::decompress; use minibench::bench; use minibench::elapsed; use rand_core::RngCore; use rand_core...
{ let mut rng = rand_chacha::ChaChaRng::seed_from_u64(0); let mut buf = vec![0u8; 100_000000]; rng.fill_bytes(&mut buf); let compressed = compress(&buf).unwrap(); bench("compress (100M)", || { elapsed(|| { compress(&buf).unwrap(); }) }); bench("decompress (~100M...
identifier_body
bench.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use lz4_pyframe::compress; use lz4_pyframe::decompress; use minibench::bench; use minibench::elapsed; use rand_core::RngCore; use rand_core...
bench("decompress (~100M)", || { elapsed(|| { decompress(&compressed).unwrap(); }) }); }
compress(&buf).unwrap(); }) });
random_line_split
bench.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use lz4_pyframe::compress; use lz4_pyframe::decompress; use minibench::bench; use minibench::elapsed; use rand_core::RngCore; use rand_core...
() { let mut rng = rand_chacha::ChaChaRng::seed_from_u64(0); let mut buf = vec![0u8; 100_000000]; rng.fill_bytes(&mut buf); let compressed = compress(&buf).unwrap(); bench("compress (100M)", || { elapsed(|| { compress(&buf).unwrap(); }) }); bench("decompress (~1...
main
identifier_name
lib.rs
// 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...
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
random_line_split
packed-struct-transmute.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// transmute // error-pattern: transmute called on types with different size #[packed] struct Foo { bar: u8, baz: uint } struct Oof { rab: u8, zab: uint } fn main() { let foo = Foo { bar: 1, baz: 10 }; unsafe { let oof: Oof = cast::transmute(foo); debug!(oof); } }
random_line_split
packed-struct-transmute.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ bar: u8, baz: uint } struct Oof { rab: u8, zab: uint } fn main() { let foo = Foo { bar: 1, baz: 10 }; unsafe { let oof: Oof = cast::transmute(foo); debug!(oof); } }
Foo
identifier_name
mod.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program 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. * * This program is distribute...
impl SCB { fn scb() -> Self { unsafe { SCB(Volatile::new(SCB_ADDR as *const _)) } } } impl Deref for SCB { type Target = RawSCB; fn deref(&self) -> &Self::Target { &*(self.0) } } impl DerefMut for SCB { fn deref_mut(&mut self) -> &mut Self::Target { ...
/// System Control Block #[derive(Copy, Clone, Debug)] pub struct SCB(Volatile<RawSCB>);
random_line_split
mod.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * This program 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. * * This program is distribute...
(&mut self) { self.icsr.set_pend_sv(); } /// Clear the pend_sv exception. pub fn clear_pend_sv(&mut self) { self.icsr.clear_pend_sv(); } }
set_pend_sv
identifier_name
csssupportsrule.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::CSSSupportsRuleBinding; use dom::bindi...
/// <https://drafts.csswg.org/css-conditional-3/#the-csssupportsrule-interface> pub fn set_condition_text(&self, text: DOMString) { let mut input = ParserInput::new(&text); let mut input = Parser::new(&mut input); let cond = SupportsCondition::parse(&mut input); if let Ok(cond)...
{ let guard = self.cssconditionrule.shared_lock().read(); let rule = self.supportsrule.read_with(&guard); rule.condition.to_css_string().into() }
identifier_body
csssupportsrule.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::CSSSupportsRuleBinding;
use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::cssconditionrule::CSSConditionRule; use dom::cssrule::SpecificCSSRule; use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use servo_arc::A...
use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods;
random_line_split
csssupportsrule.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::CSSSupportsRuleBinding; use dom::bindi...
} } impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } fn get_css(&self) -> DOMString { let guard = self.cssconditionrule.shared_lock().read(); self....
{ let global = self.global(); let win = global.as_window(); let url = win.Document().url(); let quirks_mode = win.Document().quirks_mode(); let context = ParserContext::new_for_cssom( &url, Some(CssRuleType::Supports), ...
conditional_block
csssupportsrule.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::CSSSupportsRuleBinding; use dom::bindi...
(window: &Window, parent_stylesheet: &CSSStyleSheet, supportsrule: Arc<Locked<SupportsRule>>) -> DomRoot<CSSSupportsRule> { reflect_dom_object(Box::new(CSSSupportsRule::new_inherited(parent_stylesheet, supportsrule)), window, CSSSupportsRuleBi...
new
identifier_name
coherence.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 ...
} ty::ty_tup(ref ts) => { ts.iter().any(|&t| ty_is_local(tcx, t)) } ty::ty_enum(def_id, ref substs) | ty::ty_struct(def_id, ref substs) => { def_id.krate == ast::LOCAL_CRATE || { let variances = ty::item_variances(tcx, def_id); ...
ty::ty_rptr(_, ty::mt { ty: t, .. }) => { ty_is_local(tcx, t)
random_line_split
coherence.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 ...
(infcx: &InferCtxt, impl1_def_id: ast::DefId, impl2_def_id: ast::DefId) -> bool { debug!("impl_can_satisfy(\ impl1_def_id={}, \ impl2_def_id={})", impl1_def_id.repr(infcx.tcx), impl2_def_id.repr(infcx...
impl_can_satisfy
identifier_name
coherence.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 ...
// Otherwise, at least one of the input types must be local to the // crate. trait_ref.input_types().iter().any(|&t| ty_is_local(tcx, t)) } pub fn ty_is_local(tcx: &ty::ctxt, ty: ty::t) -> bool { debug!("ty_is_local({})", ty.repr(tcx)); match ty::get(ty).sty...
{ debug!("trait {} is local to current crate", trait_ref.def_id.repr(tcx)); return true; }
conditional_block
coherence.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 ...
selcx.evaluate_impl(impl2_def_id, &obligation) } pub fn impl_is_local(tcx: &ty::ctxt, impl_def_id: ast::DefId) -> bool { debug!("impl_is_local({})", impl_def_id.repr(tcx)); // We only except this routine to be invoked on implementations // of a trait, not inh...
{ debug!("impl_can_satisfy(\ impl1_def_id={}, \ impl2_def_id={})", impl1_def_id.repr(infcx.tcx), impl2_def_id.repr(infcx.tcx)); // `impl1` provides an implementation of `Foo<X,Y> for Z`. let impl1_substs = util::fresh_substs_for_impl(infcx, DUMMY_SP, impl...
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
<T:'static>(a: &Arc<T>, b: &Arc<T>) -> bool { let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
arc_ptr_eq
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
{ let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of sty...
let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
random_line_split
main.rs
use crossbeam_channel::{bounded, select}; use crossbeam_utils::thread; fn
() { let people = vec!["Anna", "Bob", "Cody", "Dave", "Eva"]; let (s, r) = bounded(1); // Make room for one unmatched send. // Either send my name into the channel or receive someone else's, whatever happens first. let seek = |name, s, r| { select! { recv(r) -> peer => println!("{} ...
main
identifier_name
main.rs
let (s, r) = bounded(1); // Make room for one unmatched send. // Either send my name into the channel or receive someone else's, whatever happens first. let seek = |name, s, r| { select! { recv(r) -> peer => println!("{} received a message from {}.", name, peer.unwrap()), se...
use crossbeam_channel::{bounded, select}; use crossbeam_utils::thread; fn main() { let people = vec!["Anna", "Bob", "Cody", "Dave", "Eva"];
random_line_split
main.rs
use crossbeam_channel::{bounded, select}; use crossbeam_utils::thread; fn main() { let people = vec!["Anna", "Bob", "Cody", "Dave", "Eva"]; let (s, r) = bounded(1); // Make room for one unmatched send. // Either send my name into the channel or receive someone else's, whatever happens first. let seek ...
{ println!("No one received {}’s message.", name); } }
conditional_block
main.rs
use crossbeam_channel::{bounded, select}; use crossbeam_utils::thread; fn main()
// Check if there is a pending send operation. if let Ok(name) = r.try_recv() { println!("No one received {}’s message.", name); } }
{ let people = vec!["Anna", "Bob", "Cody", "Dave", "Eva"]; let (s, r) = bounded(1); // Make room for one unmatched send. // Either send my name into the channel or receive someone else's, whatever happens first. let seek = |name, s, r| { select! { recv(r) -> peer => println!("{} rec...
identifier_body
game.rs
use std::io; use std::io::Stdin; use std::error::Error; use commands::InputCommand; use game_state::GameState; use settings::Setting; use updates::Update; use player::Player; use action::Action; use strategies::Strategy; const CHARACTER: &str = "bixie"; #[derive(Debug)] enum GameStatus { New, Started, } #[d...
Setting::YourBotID(id) => { if self.player.is_some() { let mut player = self.player.take().unwrap(); player.set_id(id); self.player = Some(player); } self.your_botid = Some(id); ...
{ self.player = Some(Player::new(name.clone())); self.your_bot = Some(name); }
conditional_block
game.rs
use std::io; use std::io::Stdin; use std::error::Error; use commands::InputCommand; use game_state::GameState; use settings::Setting; use updates::Update; use player::Player; use action::Action; use strategies::Strategy; const CHARACTER: &str = "bixie"; #[derive(Debug)] enum GameStatus { New, Started, } #[d...
self.parse_command(&command_str).unwrap(); match self.status { GameStatus::New => (), GameStatus::Started => { if self.round == self.max_rounds.unwrap() { continue; } } } ...
self.stdin.read_line(&mut command_str).unwrap();
random_line_split
game.rs
use std::io; use std::io::Stdin; use std::error::Error; use commands::InputCommand; use game_state::GameState; use settings::Setting; use updates::Update; use player::Player; use action::Action; use strategies::Strategy; const CHARACTER: &str = "bixie"; #[derive(Debug)] enum GameStatus { New, Started, } #[d...
fn update_game_state(&mut self, state: String) { // For now, the game will replace the current state whenever // a new state is provided. Idealy the game should always store // previous states and perform a diff with the provided state // So it will have context (like the directio...
{ match action { Action::Character(_) => println!("{}", self.character), Action::Move(_) => { // For now I'm just ignoring timebank management // Todo: Use timebank information self.strategy.run(self.state.clone()) } } ...
identifier_body
game.rs
use std::io; use std::io::Stdin; use std::error::Error; use commands::InputCommand; use game_state::GameState; use settings::Setting; use updates::Update; use player::Player; use action::Action; use strategies::Strategy; const CHARACTER: &str = "bixie"; #[derive(Debug)] enum GameStatus { New, Started, } #[d...
(&mut self, cmd: &str) -> Result<(), &'static str> { let command = InputCommand::new(cmd).unwrap(); match command { InputCommand::Setting(val) => self.add_settings(val), InputCommand::Update(val) => self.update_game(val), InputCommand::Action(val) => self.perform_acti...
parse_command
identifier_name
network_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 https://mozilla.org/MPL/2.0/. */ //! The listener that encapsulates all state for an in-progress document request. //! Any redirects that are enco...
(&mut self, msg: FetchResponseMsg) { if self.should_send { if let Err(e) = self.sender.send((self.pipeline_id, msg)) { warn!( "Failed to forward network message to pipeline {}: {:?}", self.pipeline_id, e ); } ...
send
identifier_name
network_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 https://mozilla.org/MPL/2.0/. */ //! The listener that encapsulates all state for an in-progress document request. //! Any redirects that are enco...
Some(ref res_init_) => CoreResourceMsg::FetchRedirect( self.request_builder.clone(), res_init_.clone(), ipc_sender, None, ), None => { set_default_accept(Destination::Document, &mut listener.request_build...
let msg = match self.res_init {
random_line_split
errno.rs
use imp::errno as errno; const ZMQ_HAUSNUMERO: i32 = 156384712; pub const EACCES: i32 = errno::EACCES; pub const EADDRINUSE: i32 = errno::EADDRINUSE; pub const EAGAIN: i32 = errno::EAGAIN; pub const EBUSY: i32 = errno::EBUSY; pub const ECONNREFUSED: i32 = errno::ECONNREFUSED; ...
pub const EPROTO: i32 = errno::EPROTO; pub const EPROTONOSUPPORT: i32 = errno::EPROTONOSUPPORT; #[cfg(not(target_os = "windows"))] pub const ENOTSUP: i32 = (ZMQ_HAUSNUMERO + 1); #[cfg(target_os = "windows")] pub const ENOTSUP: i32 = errno::ENOTSUP; pub const ENOBUFS: i32 = errno:...
random_line_split
primitive_reuse_peer.rs
extern crate futures; extern crate tokio_io; use futures::future::ok; use std::cell::RefCell; use std::rc::Rc; use super::{BoxedNewPeerFuture, Peer}; use std::io::{Error as IoError, Read, Write}; use tokio_io::{AsyncRead, AsyncWrite}; use super::{once, ConstructParams, PeerConstructor, Specifier}; use futures::Futu...
else { unreachable!() } } } impl AsyncRead for PeerHandle {} impl Write for PeerHandle { fn write(&mut self, b: &[u8]) -> Result<usize, IoError> { if let Some(ref mut x) = *self.0.borrow_mut().deref_mut() { x.1.write(b) } else { unreachable!() ...
{ x.0.read(b) }
conditional_block
primitive_reuse_peer.rs
extern crate futures; extern crate tokio_io; use futures::future::ok; use std::cell::RefCell; use std::rc::Rc; use super::{BoxedNewPeerFuture, Peer};
use std::ops::DerefMut; #[derive(Debug)] pub struct Reuser(pub Rc<dyn Specifier>); impl Specifier for Reuser { fn construct(&self, p: ConstructParams) -> PeerConstructor { let send_zero_msg_on_disconnect = p.program_options.reuser_send_zero_msg_on_disconnect; let reuser = p.global(GlobalState::defa...
use std::io::{Error as IoError, Read, Write}; use tokio_io::{AsyncRead, AsyncWrite}; use super::{once, ConstructParams, PeerConstructor, Specifier}; use futures::Future;
random_line_split
primitive_reuse_peer.rs
extern crate futures; extern crate tokio_io; use futures::future::ok; use std::cell::RefCell; use std::rc::Rc; use super::{BoxedNewPeerFuture, Peer}; use std::io::{Error as IoError, Read, Write}; use tokio_io::{AsyncRead, AsyncWrite}; use super::{once, ConstructParams, PeerConstructor, Specifier}; use futures::Futu...
specifier_boilerplate!(singleconnect has_subspec globalstate); self_0_is_subspecifier!(...); } specifier_class!( name = ReuserClass, target = Reuser, prefixes = ["reuse-raw:", "raw-reuse:"], arg_handling = subspec, overlay = true, MessageBoundaryStatusDependsOnInnerType, SingleConn...
{ let send_zero_msg_on_disconnect = p.program_options.reuser_send_zero_msg_on_disconnect; let reuser = p.global(GlobalState::default).clone(); let mut reuser = reuser.clone(); let l2r = p.left_to_right.clone(); let inner = || self.0.construct(p).get_only_first_conn(l2r); ...
identifier_body
primitive_reuse_peer.rs
extern crate futures; extern crate tokio_io; use futures::future::ok; use std::cell::RefCell; use std::rc::Rc; use super::{BoxedNewPeerFuture, Peer}; use std::io::{Error as IoError, Read, Write}; use tokio_io::{AsyncRead, AsyncWrite}; use super::{once, ConstructParams, PeerConstructor, Specifier}; use futures::Futu...
(&mut self) -> futures::Poll<(), IoError> { if self.1 { let _ = self.write(b""); } if let Some(ref mut _x) = *self.0.borrow_mut().deref_mut() { // Ignore shutdown attempts Ok(futures::Async::Ready(())) //_x.1.shutdown() } else { unr...
shutdown
identifier_name
derive_from_xml_stream.rs
#[macro_use] extern crate mws_derive; #[macro_use] extern crate mws; extern crate chrono; use chrono::{DateTime, Utc}; pub use mws::{result, xmlhelper}; #[test] fn derive_struct() { #[derive(Debug, PartialEq, Default, FromXmlStream)] struct S { a: String, b: i32, date: Option<DateTime<Utc>>, } te...
Units: String, #[from_xml_stream(from_content)] Value: String, } #[derive(Debug, PartialEq, Default, FromXmlStream)] struct ItemDimensions { Height: Value, Length: Value, Width: Value, } #[derive(Debug, PartialEq, Default, FromXmlStream)] struct Products { ItemDimensions: ItemD...
struct Value { #[from_xml_stream(from_attr)]
random_line_split
derive_from_xml_stream.rs
#[macro_use] extern crate mws_derive; #[macro_use] extern crate mws; extern crate chrono; use chrono::{DateTime, Utc}; pub use mws::{result, xmlhelper}; #[test] fn
() { #[derive(Debug, PartialEq, Default, FromXmlStream)] struct S { a: String, b: i32, date: Option<DateTime<Utc>>, } test_decode!( S, r#" <a>AAA</a> <b>777</b> <date>2016-11-03T00:09:40Z</date> "#, S { a: "AAA".to_owned(), b: 777, date: Some("201...
derive_struct
identifier_name
scmstore.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::io::Write; use async_runtime::block_on; use async_runtime::stream_to_iter as block_on_stream; use clidispatch::errors; use config...
pub fn name() -> &'static str { "debugscmstore" } pub fn doc() -> &'static str { "test file and tree fetching using scmstore" }
{ let mut tree_builder = TreeStoreBuilder::new(config); tree_builder = tree_builder.suffix("manifests"); let store = tree_builder.build()?; let mut stdout = io.output(); let fetch_result = store.fetch_batch(keys.into_iter())?; let (found, missing, _errors) = fetch_result.consume(); for co...
identifier_body
scmstore.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::io::Write; use async_runtime::block_on; use async_runtime::stream_to_iter as block_on_stream; use clidispatch::errors; use config...
(opts: DebugScmStoreOpts, io: &IO, repo: Repo) -> Result<u8> { if opts.python { return Err(errors::FallbackToPython.into()); } let mode = match opts.mode.as_ref() { "file" => FetchMode::File, "tree" => FetchMode::Tree, _ => return Err(errors::Abort("'mode' must be one of 'fi...
run
identifier_name
scmstore.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::io::Write; use async_runtime::block_on; use async_runtime::stream_to_iter as block_on_stream; use clidispatch::errors; use config...
Ok(()) } pub fn name() -> &'static str { "debugscmstore" } pub fn doc() -> &'static str { "test file and tree fetching using scmstore" }
random_line_split
field.rs
use std::str::FromStr; use crate::parsers::parser; use crate::parsers::sql::Env; use crate::parsers::sql::Expr; use crate::parsers::value::PqlValue; #[derive(Debug, Default, Clone, PartialEq)] pub struct
{ pub expr: Expr, pub alias: Option<String>, } impl FromStr for Field { type Err = anyhow::Error; fn from_str(s: &str) -> anyhow::Result<Self> { match parser::expressions::parse_field(s) { Ok((_, field)) => Ok(field), Err(nom::Err::Error(err)) => { epri...
Field
identifier_name
field.rs
use std::str::FromStr; use crate::parsers::parser; use crate::parsers::sql::Env; use crate::parsers::sql::Expr; use crate::parsers::value::PqlValue; #[derive(Debug, Default, Clone, PartialEq)] pub struct Field { pub expr: Expr, pub alias: Option<String>, } impl FromStr for Field { type Err = anyhow::Erro...
pub fn evaluate(self, env: &Env) -> PqlValue { let value = self.expr.eval(&env); value } pub fn rename(self) -> (String, Expr) { if let Some(alias) = self.alias { (alias, self.expr) } else { let alias = match &self.expr { Expr::Selecto...
}
random_line_split
ptr_as_ptr.rs
// run-rustfix #![warn(clippy::ptr_as_ptr)] #![feature(custom_inner_attributes)] fn main() { let ptr: *const u32 = &42_u32; let mut_ptr: *mut u32 = &mut 42_u32; let _ = ptr as *const i32; let _ = mut_ptr as *mut i32; // Make sure the lint can handle the difference in their operator precedences. ...
() { #![clippy::msrv = "1.38"] let ptr: *const u32 = &42_u32; let mut_ptr: *mut u32 = &mut 42_u32; let _ = ptr as *const i32; let _ = mut_ptr as *mut i32; }
_msrv_1_38
identifier_name
ptr_as_ptr.rs
// run-rustfix #![warn(clippy::ptr_as_ptr)] #![feature(custom_inner_attributes)] fn main() { let ptr: *const u32 = &42_u32; let mut_ptr: *mut u32 = &mut 42_u32; let _ = ptr as *const i32; let _ = mut_ptr as *mut i32; // Make sure the lint can handle the difference in their operator precedences. ...
let _ = ptr as *const i32; let _ = mut_ptr as *mut i32; }
random_line_split
ptr_as_ptr.rs
// run-rustfix #![warn(clippy::ptr_as_ptr)] #![feature(custom_inner_attributes)] fn main() { let ptr: *const u32 = &42_u32; let mut_ptr: *mut u32 = &mut 42_u32; let _ = ptr as *const i32; let _ = mut_ptr as *mut i32; // Make sure the lint can handle the difference in their operator precedences. ...
fn _msrv_1_38() { #![clippy::msrv = "1.38"] let ptr: *const u32 = &42_u32; let mut_ptr: *mut u32 = &mut 42_u32; let _ = ptr as *const i32; let _ = mut_ptr as *mut i32; }
{ #![clippy::msrv = "1.37"] let ptr: *const u32 = &42_u32; let mut_ptr: *mut u32 = &mut 42_u32; // `pointer::cast` was stabilized in 1.38. Do not lint this let _ = ptr as *const i32; let _ = mut_ptr as *mut i32; }
identifier_body
gdt.rs
use core::mem::size_of; use core::ptr; use core::sync::atomic::{AtomicU8, Ordering}; use x86_64::structures::gdt::SegmentSelector; use x86_64::structures::tss::TaskStateSegment; use x86_64::{PrivilegeLevel, VirtAddr}; pub use x86_64::structures::gdt::Descriptor; use crate::memory::constants::GDT_ADDR; pub const DOUB...
, }; } SegmentSelector::new(index as u16, PrivilegeLevel::Ring0) } pub unsafe fn load(self) { use core::mem::size_of; use x86_64::instructions::tables::{lgdt, DescriptorTablePointer}; let ptr = DescriptorTablePointer { base: self.addr, ...
{ assert!(index + 2 < GDT_MAX_SIZE, "GDT full"); ptr::write(base.add(self.next_entry), value_low); ptr::write(base.add(self.next_entry + 1), value_high); self.next_entry += 2; }
conditional_block
gdt.rs
use core::mem::size_of; use core::ptr; use core::sync::atomic::{AtomicU8, Ordering}; use x86_64::structures::gdt::SegmentSelector; use x86_64::structures::tss::TaskStateSegment; use x86_64::{PrivilegeLevel, VirtAddr}; pub use x86_64::structures::gdt::Descriptor; use crate::memory::constants::GDT_ADDR; pub const DOUB...
(addr: VirtAddr) -> Self { Self { addr, next_entry: 1, // first entry is the null descriptor, so it is not free } } pub fn add_entry(&mut self, entry: Descriptor) -> SegmentSelector { let base: *mut u64 = self.addr.as_mut_ptr(); let index = self.next_entr...
new
identifier_name
gdt.rs
use core::mem::size_of; use core::ptr; use core::sync::atomic::{AtomicU8, Ordering}; use x86_64::structures::gdt::SegmentSelector; use x86_64::structures::tss::TaskStateSegment; use x86_64::{PrivilegeLevel, VirtAddr}; pub use x86_64::structures::gdt::Descriptor; use crate::memory::constants::GDT_ADDR; pub const DOUB...
pub fn add_entry(&mut self, entry: Descriptor) -> SegmentSelector { let base: *mut u64 = self.addr.as_mut_ptr(); let index = self.next_entry; unsafe { match entry { Descriptor::UserSegment(value) => { assert!(index + 1 < GDT_MAX_SIZE, "GDT fu...
{ Self { addr, next_entry: 1, // first entry is the null descriptor, so it is not free } }
identifier_body
gdt.rs
use core::mem::size_of; use core::ptr;
use core::sync::atomic::{AtomicU8, Ordering}; use x86_64::structures::gdt::SegmentSelector; use x86_64::structures::tss::TaskStateSegment; use x86_64::{PrivilegeLevel, VirtAddr}; pub use x86_64::structures::gdt::Descriptor; use crate::memory::constants::GDT_ADDR; pub const DOUBLE_FAULT_IST_INDEX: usize = 0; /// Max...
random_line_split
from_into.rs
// The From trait is used for value-to-value conversions. // If From is implemented correctly for a type, the Into trait should work conversely. // You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html #[derive(Debug)] struct Person { name: String, age: usize, } // We implement th...
#[test] fn test_missing_age() { let p: Person = Person::from("Mark,"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing_name() { let p: Person = Person::from(",1"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); }...
{ let p: Person = Person::from("Mark"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); }
identifier_body
from_into.rs
// The From trait is used for value-to-value conversions. // If From is implemented correctly for a type, the Into trait should work conversely. // You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html #[derive(Debug)] struct Person { name: String, age: usize, } // We implement th...
let p: Person = Person::from(",1"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing_name_and_age() { let p: Person = Person::from(","); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing_name...
} #[test] fn test_missing_name() {
random_line_split
from_into.rs
// The From trait is used for value-to-value conversions. // If From is implemented correctly for a type, the Into trait should work conversely. // You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html #[derive(Debug)] struct Person { name: String, age: usize, } // We implement th...
() { let p: Person = Person::from(",1"); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing_name_and_age() { let p: Person = Person::from(","); assert_eq!(p.name, "John"); assert_eq!(p.age, 30); } #[test] fn test_missing...
test_missing_name
identifier_name
variables.rs
use std::convert::TryFrom; use vm::types::Value; use vm::contexts::{LocalContext, Environment}; use vm::errors::{RuntimeErrorType, InterpreterResult as Result}; define_named_enum!(NativeVariables { ContractCaller("contract-caller"), TxSender("tx-sender"), BlockHeight("block-height"),
NativeTrue("true"), NativeFalse("false"), }); pub fn is_reserved_name(name: &str) -> bool { NativeVariables::lookup_by_name(name).is_some() } pub fn lookup_reserved_variable(name: &str, _context: &LocalContext, env: &mut Environment) -> Result<Option<Value>> { if let Some(variable) = NativeVariables::look...
BurnBlockHeight("burn-block-height"), NativeNone("none"),
random_line_split
variables.rs
use std::convert::TryFrom; use vm::types::Value; use vm::contexts::{LocalContext, Environment}; use vm::errors::{RuntimeErrorType, InterpreterResult as Result}; define_named_enum!(NativeVariables { ContractCaller("contract-caller"), TxSender("tx-sender"), BlockHeight("block-height"), BurnBlockHeight("burn-bloc...
(name: &str, _context: &LocalContext, env: &mut Environment) -> Result<Option<Value>> { if let Some(variable) = NativeVariables::lookup_by_name(name) { match variable { NativeVariables::TxSender => { let sender = env.sender.clone() .ok_or(RuntimeErrorType::NoSe...
lookup_reserved_variable
identifier_name
variables.rs
use std::convert::TryFrom; use vm::types::Value; use vm::contexts::{LocalContext, Environment}; use vm::errors::{RuntimeErrorType, InterpreterResult as Result}; define_named_enum!(NativeVariables { ContractCaller("contract-caller"), TxSender("tx-sender"), BlockHeight("block-height"), BurnBlockHeight("burn-bloc...
NativeVariables::NativeNone => { Ok(Some(Value::none())) }, NativeVariables::NativeTrue => { Ok(Some(Value::Bool(true))) }, NativeVariables::NativeFalse => { Ok(Some(Value::Bool(false))) }, } ...
{ if let Some(variable) = NativeVariables::lookup_by_name(name) { match variable { NativeVariables::TxSender => { let sender = env.sender.clone() .ok_or(RuntimeErrorType::NoSenderInContext)?; Ok(Some(sender)) }, NativeVa...
identifier_body
variables.rs
use std::convert::TryFrom; use vm::types::Value; use vm::contexts::{LocalContext, Environment}; use vm::errors::{RuntimeErrorType, InterpreterResult as Result}; define_named_enum!(NativeVariables { ContractCaller("contract-caller"), TxSender("tx-sender"), BlockHeight("block-height"), BurnBlockHeight("burn-bloc...
, NativeVariables::BurnBlockHeight => { Err(RuntimeErrorType::NotImplemented.into()) }, NativeVariables::NativeNone => { Ok(Some(Value::none())) }, NativeVariables::NativeTrue => { Ok(Some(Value::Bool(true))) ...
{ let block_height = env.global_context.database.get_current_block_height(); Ok(Some(Value::UInt(block_height as u128))) }
conditional_block
lib.rs
#[macro_use] extern crate serde_derive; extern crate chrono; extern crate hyper; extern crate hyper_native_tls; extern crate serde_json; pub mod types; pub use types::*; use std::io::Read; use hyper::Client; use hyper::client::RequestBuilder; use hyper::net::HttpsConnector; use hyper::header::{Authorization, Link, ...
/// Extract link={rel_type} values from the header collection /// /// Returns GetLinkErr if there's no link header or no link header whose rel={rel_type} fn get_link_value<'a>( headers: &hyper::header::Headers, rel_type: RelationType, ) -> Result<LinkValue, GetLinkErr> { let link = match headers.get::<Lin...
{ let client = get_client(); let mut res = get_request(&client, &ctx.token, &url, Method::Get) .send() .unwrap(); let mut content = String::new(); res.read_to_string(&mut content).unwrap(); let link_value = get_link_value(&res.headers, RelationType::Next); let data: Vec<Branch...
identifier_body
lib.rs
#[macro_use] extern crate serde_derive; extern crate chrono; extern crate hyper; extern crate hyper_native_tls; extern crate serde_json; pub mod types; pub use types::*; use std::io::Read; use hyper::Client; use hyper::client::RequestBuilder; use hyper::net::HttpsConnector; use hyper::header::{Authorization, Link, ...
fn get_branches_and_next(url: String, ctx: &Context) -> (Option<String>, Vec<Branch>) { let client = get_client(); let mut res = get_request(&client, &ctx.token, &url, Method::Get) .send() .unwrap(); let mut content = String::new(); res.read_to_string(&mut content).unwrap(); let lin...
all_branches }
random_line_split
lib.rs
#[macro_use] extern crate serde_derive; extern crate chrono; extern crate hyper; extern crate hyper_native_tls; extern crate serde_json; pub mod types; pub use types::*; use std::io::Read; use hyper::Client; use hyper::client::RequestBuilder; use hyper::net::HttpsConnector; use hyper::header::{Authorization, Link, ...
() -> Client { let ssl = NativeTlsClient::new().unwrap(); let connector = HttpsConnector::new(ssl); Client::with_connector(connector) } pub fn get_repository(ctx: &mut Context) { let url = format!("https://api.github.com/repos/{}/{}", ctx.owner, ctx.repo); let client = get_client(); let mut r...
get_client
identifier_name
app_with_file_descriptor.rs
/* Copyright 2017 Jinjing Wang This file is part of mtcp. mtcp 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. mtcp is distributed in the...
{ debug!("start_app_with_file.."); let (tun_in_sender, tun_out_receiver) = app::start_app(server); init_file_descriptor(tun_in_sender, tun_out_receiver, tun_file); }
identifier_body
app_with_file_descriptor.rs
/* Copyright 2017 Jinjing Wang This file is part of mtcp. mtcp 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. mtcp is distributed in the...
( tun_file: File, server: Server, ) { debug!("start_app_with_file.."); let (tun_in_sender, tun_out_receiver) = app::start_app(server); init_file_descriptor(tun_in_sender, tun_out_receiver, tun_file); }
start_app
identifier_name
app_with_file_descriptor.rs
/* Copyright 2017 Jinjing Wang
mtcp 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. mtcp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; witho...
This file is part of mtcp.
random_line_split
foreach-external-iterators-hashmap-break-restart.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 ...
} assert_eq!(x, 6); assert_eq!(y, 60); }
{ let mut h = HashMap::new(); let kvs = [(1, 10), (2, 20), (3, 30)]; for &(k,v) in kvs.iter() { h.insert(k,v); } let mut x = 0; let mut y = 0; let mut i = h.iter(); for (&k,&v) in i { x += k; y += v; break; } for (&k,&v) in i { x += k; ...
identifier_body
foreach-external-iterators-hashmap-break-restart.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 h = HashMap::new(); let kvs = [(1, 10), (2, 20), (3, 30)]; for &(k,v) in kvs.iter() { h.insert(k,v); } let mut x = 0; let mut y = 0; let mut i = h.iter(); for (&k,&v) in i { x += k; y += v; break; } for (&k,&v) in i { x += k...
main
identifier_name
foreach-external-iterators-hashmap-break-restart.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. extern crate col...
// http://rust-lang.org/COPYRIGHT.
random_line_split
html.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/. */ #![allow(unrooted_must_root)] use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTempl...
(*mut JSTracer); let tracer = Tracer(trc); impl HtmlTracer for Tracer { type Handle = Dom<Node>; #[allow(unrooted_must_root)] fn trace_handle(&self, node: &Dom<Node>) { unsafe { node.trace(self.0); } } ...
Tracer
identifier_name
html.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/. */ #![allow(unrooted_must_root)] use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTempl...
else { ret.push_node(node); } ret } fn push_node(&mut self, n: &Node) { match n.downcast::<Element>() { Some(e) => self .stack .push(SerializationCommand::OpenElement(DomRoot::from_ref(e))), None => self.stack.push(Seria...
{ for c in rev_children_iter(node) { ret.push_node(&*c); } }
conditional_block
html.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/. */ #![allow(unrooted_must_root)] use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTempl...
}, } } Ok(()) } }
NodeTypeId::Document(_) => panic!("Can't serialize Document node itself"), NodeTypeId::Element(_) => panic!("Element shouldn't appear here"),
random_line_split
blockhash.rs
// Implementation adapted from Python version: // https://github.com/commonsmachinery/blockhash-python/blob/e8b009d/blockhash.py // Main site: http://blockhash.io use image::{GenericImageView, Pixel}; use {BitSet, Image, HashBytes}; use std::cmp::Ordering; use std::ops::AddAssign; use std::mem; const FLOAT_EQ_MARGIN...
<T: PartialOrd>(data: &mut [T], k: usize) -> &mut T { let len = data.len(); assert!(k < len, "Called qselect_inplace with k = {} and data length: {}", k, len); if len < SORT_THRESH { data.sort_by(|left, right| left.partial_cmp(right).unwrap_or(Ordering::Less)); return &mut data[k]; } ...
qselect_inplace
identifier_name
blockhash.rs
// Implementation adapted from Python version: // https://github.com/commonsmachinery/blockhash-python/blob/e8b009d/blockhash.py // Main site: http://blockhash.io use image::{GenericImageView, Pixel}; use {BitSet, Image, HashBytes}; use std::cmp::Ordering; use std::ops::AddAssign; use std::mem; const FLOAT_EQ_MARGIN...
BitSet::from_bools( $blocks.chunks(group_len).zip(medians) .flat_map(|(blocks, median)| blocks.iter().map(move |&block| block > median || ($eq_fn(block, median) && median > cmp_factor) ) ) )...
/ (2u32 as $valty); let medians: Vec<$valty> = $blocks.chunks(group_len).map(get_median).collect();
random_line_split
blockhash.rs
// Implementation adapted from Python version: // https://github.com/commonsmachinery/blockhash-python/blob/e8b009d/blockhash.py // Main site: http://blockhash.io use image::{GenericImageView, Pixel}; use {BitSet, Image, HashBytes}; use std::cmp::Ordering; use std::ops::AddAssign; use std::mem; const FLOAT_EQ_MARGIN...
} fn partition<T: PartialOrd>(data: &mut [T]) -> usize { let len = data.len(); let pivot_idx = { let first = (&data[0], 0); let mid = (&data[len / 2], len / 2); let last = (&data[len - 1], len - 1); median_of_3(&first, &mid, &last).1 }; data.swap(pivot_idx, len - 1);...
{ qselect_inplace(&mut data[pivot_idx + 1..], k - pivot_idx - 1) }
conditional_block
blockhash.rs
// Implementation adapted from Python version: // https://github.com/commonsmachinery/blockhash-python/blob/e8b009d/blockhash.py // Main site: http://blockhash.io use image::{GenericImageView, Pixel}; use {BitSet, Image, HashBytes}; use std::cmp::Ordering; use std::ops::AddAssign; use std::mem; const FLOAT_EQ_MARGIN...
fn blockhash_slow<I: Image, B: HashBytes>(img: &I, hwidth: u32, hheight: u32) -> B { let mut blocks = vec![0f32; (hwidth * hheight) as usize]; let (iwidth, iheight) = img.dimensions(); // Block dimensions, in pixels let (block_width, block_height) = (iwidth as f32 / hwidth as f32, iheight as f32...
{ move |x, y, add| (blocks[(y as usize) * (width as usize) + (x as usize)] += add) }
identifier_body
borrowck-loan-rcvr-overloaded-op.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 ...
{ x: isize, y: isize, } impl Add<isize> for Point { type Output = isize; fn add(self, z: isize) -> isize { self.x + self.y + z } } impl Point { pub fn times(&self, z: isize) -> isize { self.x * self.y * z } } fn a() { let mut p = Point {x: 3, y: 4}; // ok (we ca...
Point
identifier_name
borrowck-loan-rcvr-overloaded-op.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 ...
// Here I create an outstanding loan and check that we get conflicts: let q = &mut p; p + 3; //~ ERROR cannot use `p` p.times(3); //~ ERROR cannot borrow `p` *q + 3; // OK to use the new alias `q` q.x += 1; // and OK to mutate it } fn main() { }
fn b() { let mut p = Point {x: 3, y: 4};
random_line_split
borrowck-loan-rcvr-overloaded-op.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 ...
fn b() { let mut p = Point {x: 3, y: 4}; // Here I create an outstanding loan and check that we get conflicts: let q = &mut p; p + 3; //~ ERROR cannot use `p` p.times(3); //~ ERROR cannot borrow `p` *q + 3; // OK to use the new alias `q` q.x += 1; // and OK to mutate it } fn main() {...
{ let mut p = Point {x: 3, y: 4}; // ok (we can loan out rcvr) p + 3; p.times(3); }
identifier_body
command.rs
use std::fmt; #[derive(Clone, Copy, Debug, PartialEq)] pub enum DroneMode { Normal = 0, TakingOff = 1, Landing = 2, TookOff = 3, // Helper mode, doesn't exist on drone Abort = 4, }
pub mode: DroneMode, pub as_array: [u8; 8], } impl Command { pub fn new() -> Command { Command { throttle: 0, yaw: 0, pitch: 0, roll: 0, mode: DroneMode::Normal, as_array: [0; 8] } } pub fn toggle_mode(&mut self, is_toggling: bool) { match self.mode { DroneMode::Normal ...
pub struct Command { pub pitch: i8, pub yaw: i8, pub roll: i8, pub throttle: i8,
random_line_split
command.rs
use std::fmt; #[derive(Clone, Copy, Debug, PartialEq)] pub enum DroneMode { Normal = 0, TakingOff = 1, Landing = 2, TookOff = 3, // Helper mode, doesn't exist on drone Abort = 4, } pub struct Command { pub pitch: i8, pub yaw: i8, pub roll: i8, pub throttle: i8, pub mode: DroneM...
, DroneMode::TakingOff => if is_toggling { () } else { self.mode = DroneMode::TookOff }, DroneMode::TookOff => if is_toggling { self.mode = DroneMode::Landing }, DroneMode::Landing => if is_toggling { () } else { self.mode = DroneMode::Normal }, DroneMode::Abort =...
{ self.mode = DroneMode::TakingOff }
conditional_block
command.rs
use std::fmt; #[derive(Clone, Copy, Debug, PartialEq)] pub enum DroneMode { Normal = 0, TakingOff = 1, Landing = 2, TookOff = 3, // Helper mode, doesn't exist on drone Abort = 4, } pub struct Command { pub pitch: i8, pub yaw: i8, pub roll: i8, pub throttle: i8, pub mode: DroneM...
() { let mut cmd = Command::new(); cmd.throttle = 127; cmd.update_array(); assert_eq!(cmd.as_array[3], 254); } #[test] fn test_throttle_down() { let mut cmd = Command::new(); cmd.throttle = -127; cmd.update_array(); assert_eq!(cmd.as_array[3...
test_throttle_up
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::RwLock; use futures::Fu...
} pub fn counters(&self) -> HashMap<&'static str, &'static Counter> { self.counters.read().unwrap().clone() } } #[cfg(test)] mod test { use super::*; #[test] fn counters_test() { static COUNTER1: Counter = Counter::new("COUNTER1"); static COUNTER2: Counter = Counter::...
{ panic!("Counter {} is duplicated", counter.name) }
conditional_block
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::RwLock; use futures::Fu...
() -> &'static Self { static REGISTRY: Lazy<Registry> = Lazy::new(Registry::default); &*REGISTRY } pub fn register_counter(&self, counter: &'static Counter) { if self .counters .write() .unwrap() .insert(counter.name, counter) .is_s...
global
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::RwLock; use futures::Fu...
fn inner(&'static self) -> &AtomicUsize { self.registered .get_or_init(|| Registry::global().register_counter(self)); &self.inner } } pub struct EntranceGuard(&'static Counter, usize); impl Drop for EntranceGuard { fn drop(&mut self) { self.0.sub(self.1); } } pub ...
{ self.add(v); EntranceGuard(self, v) }
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use std::collections::HashMap; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::RwLock; use futures::Fu...
COUNTER1.increment(); COUNTER2.add(5); let counters = Registry::global().counters(); assert_eq!(1, counters.get("COUNTER1").unwrap().value()); assert_eq!(5, counters.get("COUNTER2").unwrap().value()); } #[test] fn entrance_test() { static COUNTER3: Counter = ...
fn counters_test() { static COUNTER1: Counter = Counter::new("COUNTER1"); static COUNTER2: Counter = Counter::new("COUNTER2");
random_line_split
lib.rs
use chrono::{DateTime, Utc}; use exonum::{ blockchain::{Block, CallInBlock, CallProof, Schema, TxLocation}, crypto::Hash, helpers::Height, merkledb::{ListProof, ObjectHash, Snapshot}, messages::{AnyTx, Precommit, Verified}, runtime::{ExecutionError, ExecutionStatus}, }; use serde::{Serialize, S...
/// Returns block information for the specified height or `None` if there is no such block. pub fn block(&self, height: Height) -> Option<BlockInfo<'_>> { if self.height() >= height { Some(BlockInfo::new(self, height)) } else { None } } /// Return a blo...
{ self.schema.height() }
identifier_body
lib.rs
<Precommit>>>>, txs: RefCell<Option<Vec<Hash>>>, } impl<'a> BlockInfo<'a> { fn new(explorer: &'a BlockchainExplorer<'_>, height: Height) -> Self { let schema = explorer.schema; let hashes = schema.block_hashes_by_height(); let blocks = schema.blocks(); let block_hash = hashes ...
fmt
identifier_name
lib.rs
().as_ref() }) } /// Lists hashes of transactions included in this block. pub fn transaction_hashes(&self) -> Ref<'_, [Hash]> { if self.txs.borrow().is_none() { let txs = self.explorer.transaction_hashes(&self.header); *self.txs.borrow_mut() = Some(txs); } ...
{ UNIX_EPOCH.into() }
conditional_block
lib.rs
)] use chrono::{DateTime, Utc}; use exonum::{ blockchain::{Block, CallInBlock, CallProof, Schema, TxLocation}, crypto::Hash, helpers::Height, merkledb::{ListProof, ObjectHash, Snapshot}, messages::{AnyTx, Precommit, Verified}, runtime::{ExecutionError, ExecutionStatus}, }; use serde::{Serialize...
/// Execution error together with its location within the block. #[derive(Debug, Serialize, Deserialize)] #[non_exhaustive] pub struct ErrorWithLocation { /// Location of the error. pub location: CallInBlock, /// Error data. pub error: ExecutionError, } impl fmt::Display for ErrorWithLocation { fn...
}
random_line_split
middleware.rs
/// Macro to reduce the boilerplate required for using unboxed /// closures as `Middleware` due to current type inference behaviour. /// /// In future, the macro should hopefully be able to be removed while /// having minimal changes to the closure's code. /// /// # Limitations /// /// The body of the `middleware!` mac...
restrict_closure(move |as_pat!($req), $res_binding| { restrict(as_block!({$($b)+}), $res) }) }}; } #[doc(hidden)] #[macro_export] macro_rules! as_block { ($b:block) => ( $b ) } #[doc(hidden)] #[macro_export] macro_rules! as_pat { ($p:pat) => ( $p ) }
fn restrict_closure<F, D: Send + 'static + Sync>(f: F) -> F where F: for<'r> Fn(&'r mut Request<D>, Response<D>) -> MiddlewareResult<D> + Send + Sync { f }
random_line_split
tests.rs
extern crate bufstream; extern crate cargo; extern crate filetime; extern crate flate2; extern crate git2; extern crate hamcrest; extern crate libc; extern crate rustc_serialize; extern crate tar; extern crate tempdir; extern crate term; extern crate url; #[cfg(windows)] extern crate kernel32; #[cfg(windows)] extern cr...
mod test_cargo_registry; mod test_cargo_run; mod test_cargo_rustc; mod test_cargo_rustdoc; mod test_cargo_search; mod test_cargo_test; mod test_cargo_tool_paths; mod test_cargo_verify_project; mod test_cargo_version; mod test_shell; thread_local!(static RUSTC: Rustc = Rustc::new("rustc").unwrap()); fn rustc_host() ->...
random_line_split
tests.rs
extern crate bufstream; extern crate cargo; extern crate filetime; extern crate flate2; extern crate git2; extern crate hamcrest; extern crate libc; extern crate rustc_serialize; extern crate tar; extern crate tempdir; extern crate term; extern crate url; #[cfg(windows)] extern crate kernel32; #[cfg(windows)] extern cr...
() -> bool { RUSTC.with(|r|!(r.host.contains("msvc") &&!r.host.contains("x86_64"))) }
can_panic
identifier_name
tests.rs
extern crate bufstream; extern crate cargo; extern crate filetime; extern crate flate2; extern crate git2; extern crate hamcrest; extern crate libc; extern crate rustc_serialize; extern crate tar; extern crate tempdir; extern crate term; extern crate url; #[cfg(windows)] extern crate kernel32; #[cfg(windows)] extern cr...
{ RUSTC.with(|r| !(r.host.contains("msvc") && !r.host.contains("x86_64"))) }
identifier_body
lib.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...
#[cfg(not(test))] mod std { pub use core::ops; // RangeFull } #[cfg(test)] mod prelude { // from core. pub use core::clone::Clone; pub use core::cmp::{PartialEq, Eq, PartialOrd, Ord}; pub use core::cmp::Ordering::{Less, Equal, Greater}; pub use core::iter::range; pub use core::iter::...
{}
identifier_body
lib.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...
pub use core::iter::{ExactSizeIterator}; pub use core::marker::{Copy, Send, Sized, Sync}; pub use core::mem::drop; pub use core::ops::{Drop, Fn, FnMut, FnOnce}; pub use core::option::Option; pub use core::option::Option::{Some, None}; pub use core::ptr::PtrExt; pub use core::result::Resu...
random_line_split
lib.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...
() {} #[cfg(not(test))] mod std { pub use core::ops; // RangeFull } #[cfg(test)] mod prelude { // from core. pub use core::clone::Clone; pub use core::cmp::{PartialEq, Eq, PartialOrd, Ord}; pub use core::cmp::Ordering::{Less, Equal, Greater}; pub use core::iter::range; pub use core::i...
fixme_14344_be_sure_to_link_to_collections
identifier_name
build_gecko.rs
path }; static ref SEARCH_PATHS: Vec<PathBuf> = vec![ DISTDIR_PATH.join("include"), DISTDIR_PATH.join("include/nspr"), ]; static ref ADDED_PATHS: Mutex<HashSet<PathBuf>> = Mutex::new(HashSet::new()); static ref LAST_MODIFIED: Mutex<SystemTime> = ...
"Unrecognized line in ServoArcTypeList.h: '{}'", line )) .get(1) .unwrap() .as_str() .to_string() }) .collect() } struct BuilderWithConfig<'a> ...
{ // Read the file let mut list_file = File::open(DISTDIR_PATH.join("include/mozilla/ServoArcTypeList.h")) .expect("Unable to open ServoArcTypeList.h"); let mut content = String::new(); list_file .read_to_string(&mut content) .expect("Fail to read Serv...
identifier_body
build_gecko.rs
path }; static ref SEARCH_PATHS: Vec<PathBuf> = vec![ DISTDIR_PATH.join("include"), DISTDIR_PATH.join("include/nspr"), ]; static ref ADDED_PATHS: Mutex<HashSet<PathBuf>> = Mutex::new(HashSet::new()); static ref LAST_MODIFIED: Mutex<SystemTime> = ...
(self, ty: &str, structs_list: &HashSet<&str>) -> Builder { if!structs_list.contains(ty) { self.blacklist_type(ty) .raw_line(format!("enum {}Void {{ }}", ty)) .raw_line(format!("pub struct {0}({0}Void);", ty)) } else { self ...
zero_size_type
identifier_name