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 |
|---|---|---|---|---|
all.rs | use std::collections::HashMap;
use protobuf::descriptor::FileDescriptorProto;
use protobuf::reflect::FileDescriptor;
use protobuf_parse::ProtoPath;
use protobuf_parse::ProtoPathBuf;
use crate::compiler_plugin;
use crate::customize::ctx::CustomizeElemCtx;
use crate::customize::CustomizeCallback;
use crate::gen::file::... |
for file_name in files_to_generate {
let file = files_map.get(file_name.as_path()).expect(&format!(
"file not found in file descriptors: {:?}, files: {:?}",
file_name,
files_map.keys()
));
let gen_file_result = gen_file(file, &files_map, &root_scope, &cus... | {
let file_descriptors = FileDescriptor::new_dynamic_fds(file_descriptors.to_vec())?;
let root_scope = RootScope {
file_descriptors: &file_descriptors,
};
let mut results: Vec<compiler_plugin::GenResult> = Vec::new();
let files_map: HashMap<&ProtoPath, &FileDescriptor> = file_descriptors
... | identifier_body |
all.rs | use std::collections::HashMap;
use protobuf::descriptor::FileDescriptorProto;
use protobuf::reflect::FileDescriptor;
use protobuf_parse::ProtoPath;
use protobuf_parse::ProtoPathBuf;
use crate::compiler_plugin;
use crate::customize::ctx::CustomizeElemCtx;
use crate::customize::CustomizeCallback;
use crate::gen::file::... | callback: customize_callback,
};
for file_name in files_to_generate {
let file = files_map.get(file_name.as_path()).expect(&format!(
"file not found in file descriptors: {:?}, files: {:?}",
file_name,
files_map.keys()
));
let gen_file_result =... | for_children: customize.clone(), | random_line_split |
htmltitleelement.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::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... | }
}
content
}
// http://www.whatwg.org/html/#dom-title-text
fn SetText(self, value: DOMString) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.SetTextContent(Some(value))
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLTitleElement> {
fn super_typ... | Some(text) => content.push_str(text.characterdata().data().as_slice()),
None => (), | random_line_split |
htmltitleelement.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::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... | <'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn bind_to_tree(&self, is_in_doc: bool) {
let node: JSRef<Node> = NodeCast::from_ref(*self);
if is_in_doc {
... | super_type | identifier_name |
htmltitleelement.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::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... |
}
}
| {
let document = node.owner_doc().root();
document.r().send_title_to_compositor()
} | conditional_block |
htmltitleelement.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::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElem... |
}
impl HTMLTitleElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTitleElement {
HTMLTitleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTitleElement, localName, prefix, document)
}
}
#[allow... | {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTitleElement)))
} | identifier_body |
lib.rs | //! Backend API for wayland crates
#![warn(missing_docs, missing_debug_implementations)]
#![forbid(improper_ctypes, unsafe_op_in_unsafe_fn)]
pub extern crate smallvec;
/// Helper macro for quickly making a [`Message`](crate::protocol::Message)
#[macro_export]
macro_rules! message {
($sender_id: expr, $opcode: ex... | {
let cstr = unsafe { std::ffi::CStr::from_ptr(msg) };
let text = cstr.to_string_lossy();
log::error!("{}", text);
} | identifier_body | |
lib.rs | //! Backend API for wayland crates | #![forbid(improper_ctypes, unsafe_op_in_unsafe_fn)]
pub extern crate smallvec;
/// Helper macro for quickly making a [`Message`](crate::protocol::Message)
#[macro_export]
macro_rules! message {
($sender_id: expr, $opcode: expr, [$($args: expr),* $(,)?] $(,)?) => {
$crate::protocol::Message {
s... |
#![warn(missing_docs, missing_debug_implementations)] | random_line_split |
lib.rs | //! Backend API for wayland crates
#![warn(missing_docs, missing_debug_implementations)]
#![forbid(improper_ctypes, unsafe_op_in_unsafe_fn)]
pub extern crate smallvec;
/// Helper macro for quickly making a [`Message`](crate::protocol::Message)
#[macro_export]
macro_rules! message {
($sender_id: expr, $opcode: ex... | (msg: *const std::os::raw::c_char) {
let cstr = unsafe { std::ffi::CStr::from_ptr(msg) };
let text = cstr.to_string_lossy();
log::error!("{}", text);
}
#[no_mangle]
extern "C" fn wl_log_rust_logger_server(msg: *const std::os::raw::c_char) {
let cstr = unsafe { std::ffi::CStr::from_ptr(msg) };
let t... | wl_log_rust_logger_client | identifier_name |
dir.rs | use std::io;
use std::fs;
use std::path::{Path, PathBuf};
use std::slice::Iter as SliceIter;
use feature::Git;
use file::{File, fields};
/// A **Dir** provides a cached list of the file paths in a directory that's
/// being listed.
///
/// This object gets passed to the Files themselves, in order for them to
/// che... |
} | {
self.inner.next().map(|path| File::from_path(path, Some(self.dir)).map_err(|t| (path.clone(), t)))
} | identifier_body |
dir.rs | use std::io;
use std::fs;
use std::path::{Path, PathBuf};
use std::slice::Iter as SliceIter;
use feature::Git;
use file::{File, fields};
/// A **Dir** provides a cached list of the file paths in a directory that's
/// being listed. | /// accordingly. (See `File#get_source_files`)
pub struct Dir {
/// A vector of the files that have been read from this directory.
contents: Vec<PathBuf>,
/// The path that was read.
pub path: PathBuf,
/// Holds a `Git` object if scanning for Git repositories is switched on,
/// and this dire... | ///
/// This object gets passed to the Files themselves, in order for them to
/// check the existence of surrounding files, then highlight themselves | random_line_split |
dir.rs | use std::io;
use std::fs;
use std::path::{Path, PathBuf};
use std::slice::Iter as SliceIter;
use feature::Git;
use file::{File, fields};
/// A **Dir** provides a cached list of the file paths in a directory that's
/// being listed.
///
/// This object gets passed to the Files themselves, in order for them to
/// che... | ,
})
}
/// Produce an iterator of IO results of trying to read all the files in
/// this directory.
pub fn files<'dir>(&'dir self) -> Files<'dir> {
Files {
inner: self.contents.iter(),
dir: &self,
}
}
/// Whether this directory contains a file wi... | { None } | conditional_block |
dir.rs | use std::io;
use std::fs;
use std::path::{Path, PathBuf};
use std::slice::Iter as SliceIter;
use feature::Git;
use file::{File, fields};
/// A **Dir** provides a cached list of the file paths in a directory that's
/// being listed.
///
/// This object gets passed to the Files themselves, in order for them to
/// che... | <'dir>(&'dir self) -> Files<'dir> {
Files {
inner: self.contents.iter(),
dir: &self,
}
}
/// Whether this directory contains a file with the given path.
pub fn contains(&self, path: &Path) -> bool {
self.contents.iter().any(|ref p| p.as_path() == path)
}
... | files | identifier_name |
liveness-unused.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
fn f5a() {
for x in 1..10 { }
//~^ ERROR unused variable: `x`
}
fn f5b() {
for (x, _) in [1, 2, 3].iter().enumerate() { }
//~^ ERROR unused variable: `x`
}
fn f5c() {
for (_, x) in [1, 2, 3].iter().enumerate() {
//~^ ERROR unused variable: `x`
continue;
drop(*x as i32... | {
i
} | conditional_block |
liveness-unused.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn f3() {
let mut x = 3;
//~^ ERROR variable `x` is assigned to, but never used
x += 4;
//~^ ERROR value assigned to `x` is never read
}
fn f3b() {
let mut z = 3;
//~^ ERROR variable `z` is assigned to, but never used
loop {
z += 4;
}
}
#[allow(unused_variables)]
fn f3c() {
... | {
let x = 3;
//~^ ERROR unused variable: `x`
} | identifier_body |
liveness-unused.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
fn main() {
} | //~^ ERROR unused variable: `x`
continue;
drop(*x as i32); //~ WARNING unreachable statement | random_line_split |
liveness-unused.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 ... | {
a(isize), b(isize), c(isize)
}
fn f4b() -> isize {
match tri::a(3) {
tri::a(i) | tri::b(i) | tri::c(i) => {
i
}
}
}
fn f5a() {
for x in 1..10 { }
//~^ ERROR unused variable: `x`
}
fn f5b() {
for (x, _) in [1, 2, 3].iter().enumerate() { }
//~^ ERROR unused variable: ... | tri | identifier_name |
breakaesecb.rs | use std::env;
use std::io;
use std::io::Write;
use common::{err, ascii, util, challenge};
use common::cipher::oracle;
use common::cipher::cipherbox as cb;
pub static info: challenge::Info = challenge::Info {
no: 12,
title: "Byte-at-a-time ECB decryption (Simple)",
help: "param1: path t... |
}
let plaintext = try!(ascii::raw_to_str(&plainraw));
Ok(plaintext)
}
pub fn detect_blocksize_plainsize(cbox: &cb::CipherBox, max: usize) -> Result<(usize, usize), err::Error> {
let len1 = try!(cbox.encrypt(&Vec::<u8>::new())).len();
let mut prefix = vec![65 as u8];
for _ in 0.. max {
... | {
prefix = vec![65 as u8; blocksize - 1];
block_no += 1;
} | conditional_block |
breakaesecb.rs | use std::env;
use std::io;
use std::io::Write;
use common::{err, ascii, util, challenge};
use common::cipher::oracle;
use common::cipher::cipherbox as cb;
pub static info: challenge::Info = challenge::Info {
no: 12,
title: "Byte-at-a-time ECB decryption (Simple)",
help: "param1: path t... | () -> err::ExitCode {
let input_filepath = match env::args().nth(2) {
Some(v) => v,
None => { println!("please specify input data (base64 encoded) filepath"); return exit_err!(); }
};
let cbox = rtry!(cb::init_from_file(&input_filepath), exit_err!());
rtry!(break_aes_ecb(&cbox), exit... | interactive | identifier_name |
breakaesecb.rs | use std::env;
use std::io;
use std::io::Write;
use common::{err, ascii, util, challenge};
use common::cipher::oracle;
use common::cipher::cipherbox as cb;
pub static info: challenge::Info = challenge::Info {
no: 12,
title: "Byte-at-a-time ECB decryption (Simple)",
help: "param1: path t... | {
let input_filepath = match env::args().nth(2) {
Some(v) => v,
None => { println!("please specify input data (base64 encoded) filepath"); return exit_err!(); }
};
let cbox = rtry!(cb::init_from_file(&input_filepath), exit_err!());
rtry!(break_aes_ecb(&cbox), exit_err!());
exit_... | identifier_body | |
breakaesecb.rs | use std::env;
use std::io;
use std::io::Write;
use common::{err, ascii, util, challenge};
use common::cipher::oracle;
use common::cipher::cipherbox as cb;
pub static info: challenge::Info = challenge::Info {
no: 12,
title: "Byte-at-a-time ECB decryption (Simple)",
help: "param1: path t... | //println!("{} - {}", printr!(&prefix), printr!(&dict_prefix));
let cipher = try!(cbox.encrypt(&prefix));
let dict = try!(cb::make_dict(&dict_prefix, &cbox, max_u8));
let cipher_block: Vec<u8> = cipher.chunks(blocksize).nth(block_no).unwrap().to_vec();
let mut raw_char: u8 = 0... | let mut dict_prefix = prefix.clone();
for i in 0 .. plaintext_size { | random_line_split |
validate_no_inline_with_raw_response_type.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::no_inline::{
is_raw_response_type_enabled, NO_INLINE_DIRECTIVE_NAME, RAW_RESPONSE_TYPE_NAME,
};
use common::{Diagn... |
fn validate_fragment(&mut self, fragment: &FragmentDefinition) -> DiagnosticsResult<()> {
if let Some(directive) = fragment.directives.named(*NO_INLINE_DIRECTIVE_NAME) {
if!is_raw_response_type_enabled(directive) {
return Err(vec![
Diagnostic::error(
... | {
validate_map(program.operations(), |operation| {
if operation
.directives
.named(*RAW_RESPONSE_TYPE_NAME)
.is_some()
{
self.current_query_location = operation.name.location;
self.default_validate_operation(... | identifier_body |
validate_no_inline_with_raw_response_type.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::no_inline::{
is_raw_response_type_enabled, NO_INLINE_DIRECTIVE_NAME, RAW_RESPONSE_TYPE_NAME,
};
use common::{Diagn... | (program: &'a Program) -> Self {
Self {
validated: Default::default(),
current_query_location: Location::new(SourceLocationKey::generated(), Span::empty()),
program,
}
}
}
impl<'a> Validator for NoInlineRawResponseTypeValidator<'a> {
const NAME: &'static str ... | new | identifier_name |
validate_no_inline_with_raw_response_type.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::no_inline::{
is_raw_response_type_enabled, NO_INLINE_DIRECTIVE_NAME, RAW_RESPONSE_TYPE_NAME,
};
use common::{Diagn... | Self {
validated: Default::default(),
current_query_location: Location::new(SourceLocationKey::generated(), Span::empty()),
program,
}
}
}
impl<'a> Validator for NoInlineRawResponseTypeValidator<'a> {
const NAME: &'static str = "NoInlineRawResponseTypeValidat... | fn new(program: &'a Program) -> Self { | random_line_split |
validate_no_inline_with_raw_response_type.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::no_inline::{
is_raw_response_type_enabled, NO_INLINE_DIRECTIVE_NAME, RAW_RESPONSE_TYPE_NAME,
};
use common::{Diagn... |
})
}
fn validate_fragment(&mut self, fragment: &FragmentDefinition) -> DiagnosticsResult<()> {
if let Some(directive) = fragment.directives.named(*NO_INLINE_DIRECTIVE_NAME) {
if!is_raw_response_type_enabled(directive) {
return Err(vec![
Diagnosti... | {
Ok(())
} | conditional_block |
different_defining_uses_never_type2.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | if arg {
loop {}
} else {
"boo"
}
}
fn bar2(arg: bool) -> Foo {
if arg {
"bar2"
} else {
panic!()
}
}
fn boo2(arg: bool) -> Foo {
if arg {
"boo2"
} else {
loop {}
}
} | }
}
fn boo(arg: bool) -> Foo { | random_line_split |
different_defining_uses_never_type2.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (arg: bool) -> Foo {
if arg {
"boo2"
} else {
loop {}
}
}
| boo2 | identifier_name |
different_defining_uses_never_type2.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
"bar"
}
}
fn boo(arg: bool) -> Foo {
if arg {
loop {}
} else {
"boo"
}
}
fn bar2(arg: bool) -> Foo {
if arg {
"bar2"
} else {
panic!()
}
}
fn boo2(arg: bool) -> Foo {
if arg {
"boo2"
} else {
loop {}
}
}
| {
panic!()
} | conditional_block |
different_defining_uses_never_type2.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
if arg {
"boo2"
} else {
loop {}
}
} | identifier_body | |
bin.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use std::{fs, io::Write, path::Path};
use error_code::*;
fn main() | f.write_all(s.as_bytes()).unwrap();
});
f.sync_all().unwrap();
}
| {
let err_codes = vec![
cloud::ALL_ERROR_CODES.iter(),
codec::ALL_ERROR_CODES.iter(),
coprocessor::ALL_ERROR_CODES.iter(),
encryption::ALL_ERROR_CODES.iter(),
engine::ALL_ERROR_CODES.iter(),
pd::ALL_ERROR_CODES.iter(),
raft::ALL_ERROR_CODES.iter(),
raf... | identifier_body |
bin.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use std::{fs, io::Write, path::Path};
use error_code::*;
fn main() {
let err_codes = vec![
cloud::ALL_ERROR_CODES.iter(),
codec::ALL_ERROR_CODES.iter(),
coprocessor::ALL_ERROR_CODES.iter(), | encryption::ALL_ERROR_CODES.iter(),
engine::ALL_ERROR_CODES.iter(),
pd::ALL_ERROR_CODES.iter(),
raft::ALL_ERROR_CODES.iter(),
raftstore::ALL_ERROR_CODES.iter(),
sst_importer::ALL_ERROR_CODES.iter(),
storage::ALL_ERROR_CODES.iter(),
];
let path = Path::new(... | random_line_split | |
bin.rs | // Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use std::{fs, io::Write, path::Path};
use error_code::*;
fn | () {
let err_codes = vec![
cloud::ALL_ERROR_CODES.iter(),
codec::ALL_ERROR_CODES.iter(),
coprocessor::ALL_ERROR_CODES.iter(),
encryption::ALL_ERROR_CODES.iter(),
engine::ALL_ERROR_CODES.iter(),
pd::ALL_ERROR_CODES.iter(),
raft::ALL_ERROR_CODES.iter(),
... | main | identifier_name |
mod.rs | iates a
//! disconnect from the peer. It relies on ConnectivityManager or the remote peer to re-establish
//! the connection.
//!
//! Future Work
//! -----------
//! We can make a few other improvements to the health checker. These are:
//! - Make the policy for interpreting ping failures pluggable
//! - Use successful... | (u32);
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Pong(u32);
/// The actor performing health checks by running the Ping protocol
pub struct HealthChecker {
network_context: Arc<NetworkContext>,
/// A handle to a time service for easily mocking time-related operations.
time_service: TimeSer... | Ping | identifier_name |
mod.rs | iates a
//! disconnect from the peer. It relies on ConnectivityManager or the remote peer to re-establish
//! the connection.
//!
//! Future Work
//! -----------
//! We can make a few other improvements to the health checker. These are:
//! - Make the policy for interpreting ping failures pluggable
//! - Use successful... | warn!(
SecurityEvent::InvalidHealthCheckerMsg,
NetworkSchema::new(&self.network_context).remote_peer(&peer_id),
"{} Pong nonce doesn't match Ping nonce. Round: {}, Pong: {}, Ping: {}",
self.network_contex... | {
if pong.0 == req_nonce {
trace!(
NetworkSchema::new(&self.network_context).remote_peer(&peer_id),
rount = round,
"{} Ping successful for peer: {} round: {}",
self.network_context,
... | conditional_block |
mod.rs | initiates a
//! disconnect from the peer. It relies on ConnectivityManager or the remote peer to re-establish
//! the connection.
//!
//! Future Work
//! -----------
//! We can make a few other improvements to the health checker. These are:
//! - Make the policy for interpreting ping failures pluggable
//! - Use succe... | mod test;
/// The interface from Network to HealthChecker layer.
///
/// `HealthCheckerNetworkEvents` is a `Stream` of `PeerManagerNotification` where the
/// raw `Bytes` rpc messages are deserialized into
/// `HealthCheckerMsg` types. `HealthCheckerNetworkEvents` is a thin wrapper
/// around an `channel::Receiver<Pee... | use short_hex_str::AsShortHexStr;
use std::{collections::HashMap, sync::Arc, time::Duration};
pub mod builder;
#[cfg(test)] | random_line_split |
mod.rs | iates a
//! disconnect from the peer. It relies on ConnectivityManager or the remote peer to re-establish
//! the connection.
//!
//! Future Work
//! -----------
//! We can make a few other improvements to the health checker. These are:
//! - Make the policy for interpreting ping failures pluggable
//! - Use successful... | });
} else {
warn!(
SecurityEvent::InvalidHealthCheckerMsg,
NetworkSchema::new(&self.network_context).remote_peer(&peer_id),
"{} Pong nonce doesn't match Ping nonce. Round: {}, Pong: {}, P... | {
match ping_result {
Ok(pong) => {
if pong.0 == req_nonce {
trace!(
NetworkSchema::new(&self.network_context).remote_peer(&peer_id),
rount = round,
"{} Ping successful for peer: {} round: {}"... | identifier_body |
test-ignore-cfg.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 ... | () {
}
#[test]
#[ignore(cfg(noignorecfg))]
fn shouldnotignore() {
}
#[test]
fn checktests() {
// Pull the tests out of the secreturn test module
let tests = __test::tests;
assert!(
tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldignore" && t.desc.ignore));
assert!(
tests.iter()... | shouldignore | identifier_name |
test-ignore-cfg.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!(
tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldnotignore" &&!t.desc.ignore));
} |
assert!(
tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldignore" && t.desc.ignore)); | random_line_split |
test-ignore-cfg.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 ... | {
// Pull the tests out of the secreturn test module
let tests = __test::tests;
assert!(
tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldignore" && t.desc.ignore));
assert!(
tests.iter().any_(|t| t.desc.name.to_str() == ~"shouldnotignore" && !t.desc.ignore));
} | identifier_body | |
uberblock.rs | use redox::{mem, ptr};
use redox::{String, ToString};
use super::from_bytes::FromBytes;
use super::block_ptr::BlockPtr;
#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct Uberblock {
pub magic: u64,
pub version: u64,
pub txg: u64,
pub guid_sum: u64,
pub timestamp: u64,
pub rootbp: BlockP... |
}
impl FromBytes for Uberblock {
fn from_bytes(data: &[u8]) -> Result<Self, String> {
if data.len() >= mem::size_of::<Uberblock>() {
let uberblock = unsafe { ptr::read(data.as_ptr() as *const Uberblock) };
if uberblock.magic == Uberblock::magic_little() {
return Ok... | {
return 0x00bab10c;
} | identifier_body |
uberblock.rs | use redox::{mem, ptr};
use redox::{String, ToString};
use super::from_bytes::FromBytes;
use super::block_ptr::BlockPtr;
#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct Uberblock {
pub magic: u64,
pub version: u64,
pub txg: u64,
pub guid_sum: u64,
pub timestamp: u64,
pub rootbp: BlockP... | if uberblock.magic == Uberblock::magic_little() {
return Ok(uberblock);
} else if uberblock.magic == Uberblock::magic_big() {
return Ok(uberblock);
}
}
Err("Error: cannot find Uberblock".to_string())
}
} | impl FromBytes for Uberblock {
fn from_bytes(data: &[u8]) -> Result<Self, String> {
if data.len() >= mem::size_of::<Uberblock>() {
let uberblock = unsafe { ptr::read(data.as_ptr() as *const Uberblock) }; | random_line_split |
uberblock.rs | use redox::{mem, ptr};
use redox::{String, ToString};
use super::from_bytes::FromBytes;
use super::block_ptr::BlockPtr;
#[derive(Copy, Clone, Debug)]
#[repr(packed)]
pub struct Uberblock {
pub magic: u64,
pub version: u64,
pub txg: u64,
pub guid_sum: u64,
pub timestamp: u64,
pub rootbp: BlockP... | () -> u64 {
return 0x00bab10c;
}
}
impl FromBytes for Uberblock {
fn from_bytes(data: &[u8]) -> Result<Self, String> {
if data.len() >= mem::size_of::<Uberblock>() {
let uberblock = unsafe { ptr::read(data.as_ptr() as *const Uberblock) };
if uberblock.magic == Uberblock... | magic_big | identifier_name |
coherence-overlap-downstream-inherent.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 ... | {} | identifier_body | |
coherence-overlap-downstream-inherent.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 ... | struct A<T, X>(T, X);
impl<X, T> A<T, X> where T: Bar<X> { fn f(&self) {} }
//~^ ERROR E0592
impl<X> A<i32, X> { fn f(&self) {} }
fn main() {} | trait Bar<X> {} | random_line_split |
coherence-overlap-downstream-inherent.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 ... | (&self) { } }
trait Bar<X> {}
struct A<T, X>(T, X);
impl<X, T> A<T, X> where T: Bar<X> { fn f(&self) {} }
//~^ ERROR E0592
impl<X> A<i32, X> { fn f(&self) {} }
fn main() {}
| dummy | identifier_name |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::binding... | (&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _... | Validity | identifier_name |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::binding... | impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// Note: this function currently only exists for union.html... | }
}
| random_line_split |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::binding... | else {
node.check_disabled_attribute();
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match local_name {
&atom!("size") => AttrValue::from_u32(value, DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_... | {
node.check_ancestors_disabled_state_for_form_control();
} | conditional_block |
htmlselectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::{Attr, AttrValue};
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::binding... |
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
node.check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
... | {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!(disabled) {
let node = NodeCast::from_ref(self);
match mutation {
AttributeMutation::Set(_) => {
node.set_disabled_state(true);
n... | identifier_body |
date.rs | use std::fmt;
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use header::parsing::from_one_raw_str;
use header::parsing::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
#[derive(Copy, PartialEq, Clone, Debug)]
pub struct Date(pub Tm)... |
}
bench_header!(imf_fixdate, Date, { vec![b"Sun, 07 Nov 1994 08:48:37 GMT".to_vec()] });
bench_header!(rfc_850, Date, { vec![b"Sunday, 06-Nov-94 08:49:37 GMT".to_vec()] });
bench_header!(asctime, Date, { vec![b"Sun Nov 6 08:49:37 1994".to_vec()] });
| {
tm_from_str(s).map(Date).ok_or(())
} | identifier_body |
date.rs | use std::fmt;
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use header::parsing::from_one_raw_str;
use header::parsing::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
#[derive(Copy, PartialEq, Clone, Debug)]
pub struct Date(pub Tm)... | "Date"
}
fn parse_header(raw: &[Vec<u8>]) -> Option<Date> {
from_one_raw_str(raw)
}
}
impl HeaderFormat for Date {
fn fmt_header(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let tm = self.0;
let tm = match tm.tm_utcoff {
0 => tm,
_ => tm.to... | deref!(Date => Tm);
impl Header for Date {
fn header_name() -> &'static str { | random_line_split |
date.rs | use std::fmt;
use std::str::FromStr;
use time::Tm;
use header::{Header, HeaderFormat};
use header::parsing::from_one_raw_str;
use header::parsing::tm_from_str;
// Egh, replace as soon as something better than time::Tm exists.
/// The `Date` header field.
#[derive(Copy, PartialEq, Clone, Debug)]
pub struct Date(pub Tm)... | (&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let tm = self.0;
let tm = match tm.tm_utcoff {
0 => tm,
_ => tm.to_utc(),
};
fmt::Display::fmt(&tm.rfc822(), fmt)
}
}
impl FromStr for Date {
type Err = ();
fn from_str(s: &str) -> Result<Date, ()> {
... | fmt_header | identifier_name |
smallest-hello-world.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... |
#[lang = "fail_fmt"] fn fail_fmt() ->! { loop {} }
#[start]
#[no_stack_check]
fn main(_: int, _: *const *const u8) -> int {
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
}
| {} | identifier_body |
smallest-hello-world.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... | (_: int, _: *const *const u8) -> int {
unsafe {
let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
}
| main | identifier_name |
smallest-hello-world.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... | let (ptr, _): (*const u8, uint) = transmute("Hello!\0");
puts(ptr);
}
return 0;
} | fn main(_: int, _: *const *const u8) -> int {
unsafe { | random_line_split |
result.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 ... |
}
let bad_err: Result<isize, &'static str> = Err("Unrecoverable mess.");
let _ : isize = bad_err.unwrap_or_else(handler);
}
#[test]
pub fn test_expect_ok() {
let ok: Result<isize, &'static str> = Ok(100);
assert_eq!(ok.expect("Unexpected error"), 100);
}
#[test]
#[should_panic(expected="Got expe... | {
panic!("BadBad")
} | conditional_block |
result.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[test]
fn test_unwrap_or_else() {
fn handler(msg: &'static str) -> isize {
if msg == "I got this." {
50
} else {
panic!("BadBad")
}
}
let ok: Result<isize, &'static str> = Ok(100);
let ok_err: Result<isize, &'static str> = Err("I got this.");
asse... | {
let ok: Result<isize, &'static str> = Ok(100);
let ok_err: Result<isize, &'static str> = Err("Err");
assert_eq!(ok.unwrap_or(50), 100);
assert_eq!(ok_err.unwrap_or(50), 50);
} | identifier_body |
result.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | fn test_or_else() {
assert_eq!(op1().or_else(|_| Ok::<isize, &'static str>(667)).unwrap(), 666);
assert_eq!(op1().or_else(|e| Err::<isize, &'static str>(e)).unwrap(), 666);
assert_eq!(op2().or_else(|_| Ok::<isize, &'static str>(667)).unwrap(), 667);
assert_eq!(op2().or_else(|e| Err::<isize, &'static st... | assert_eq!(op2().or(Err("bad")).unwrap_err(), "bad");
}
#[test] | random_line_split |
result.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 ... | () -> Result<isize, &'static str> { Err("sadface") }
#[test]
fn test_and() {
assert_eq!(op1().and(Ok(667)).unwrap(), 667);
assert_eq!(op1().and(Err::<i32, &'static str>("bad")).unwrap_err(),
"bad");
assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface");
assert_eq!(op2().and(Err::<i32,&... | op2 | identifier_name |
types.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
#[test]
fn serialize_output() {
let hex_commit = "{\
\"commit\":\"083eafae5d61a85ab07b12e1a51b3918d8e6de11fc6cde641d54af53608aa77b9f\",\
\"height\":0,\
\"mmr_index\":0\
}";
let deserialized: Output = serde_json::from_str(&hex_commit).unwrap();
let serialized = serde_json::to_string(&deserializ... | {
let hex_output = "{\
\"output_type\":\"Coinbase\",\
\"commit\":\"083eafae5d61a85ab07b12e1a51b3918d8e6de11fc6cde641d54af53608aa77b9f\",\
\"spent\":false,\
\"proof\":null,\
\"proof_hash\":\"ed6ba96009b86173bade6a9227ed60422916593fa32dd6d78b25b7a4eeef4946\",\
\"block_height\":0,\
\"merkle_p... | identifier_body |
types.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | MmrIndex,
}
struct OutputPrintableVisitor;
impl<'de> serde::de::Visitor<'de> for OutputPrintableVisitor {
type Value = OutputPrintable;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a print able Output")
}
fn visit_map<A>(self, mut map: A) -> ... | Spent,
Proof,
ProofHash,
BlockHeight,
MerkleProof, | random_line_split |
types.rs | // Copyright 2021 The Grin Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | (tip: chain::Tip) -> Tip {
Tip {
height: tip.height,
last_block_pushed: tip.last_block_h.to_hex(),
prev_block_to_last: tip.prev_block_h.to_hex(),
total_difficulty: tip.total_difficulty.to_num(),
}
}
}
/// Status page containing different server information
#[derive(Serialize, Deserialize, Debug, Clone... | from_tip | identifier_name |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventH... |
#[dom_struct]
pub struct HTMLBodyElement {
htmlelement: HTMLElement
}
impl HTMLBodyElementDerived for EventTarget {
fn is_htmlbodyelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLBodyElementTypeId))
}
}
impl HTMLBodyElement {
fn new_inherited(localName: DOMSt... | random_line_split | |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventH... | {
htmlelement: HTMLElement
}
impl HTMLBodyElementDerived for EventTarget {
fn is_htmlbodyelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLBodyElementTypeId))
}
}
impl HTMLBodyElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document... | HTMLBodyElement | identifier_name |
htmlbodyelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventH... |
fn after_set_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.after_set_attr(attr),
_ => (),
}
let name = attr.local_name().as_slice();
if name.starts_with("on") {
static FORWARDED_EVENTS: &'static [&'static str] =
... | {
let element: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(element as &VirtualMethods)
} | identifier_body |
lib.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law o... |
/// Wrapper around a termination signal [`oneshot::Sender`] and the [`JoinHandle`] of the associated
/// background task, created by [`background`].
pub struct Background<T> {
term_tx: oneshot::Sender<()>,
join_handle: JoinHandle<T>,
}
impl<T> Background<T> {
/// Sends the termination signal to the backg... | {
port_check::free_local_port().expect("could not pick free local port")
} | identifier_body |
lib.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law o... | {
pub elapsed: Duration,
pub response: Response,
}
pub async fn make_request(port: u16, request_body: &[u8]) -> TestResult {
let uri = format!("http://localhost:{}/", port);
// Create client
let mut client = oak_functions_client::Client::new(&uri, |_config| Ok(()))
.await
.expect("C... | TestResult | identifier_name |
lib.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law o... | port_check::free_local_port().expect("could not pick free local port")
}
/// Wrapper around a termination signal [`oneshot::Sender`] and the [`JoinHandle`] of the associated
/// background task, created by [`background`].
pub struct Background<T> {
term_tx: oneshot::Sender<()>,
join_handle: JoinHandle<T>,
... | }
pub fn free_port() -> u16 { | random_line_split |
common.rs |
macro_rules! enum_number {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum $name {
$($variant = $value,)*
}
impl serde::Serialize for $name {
fn s... | use chrono::NaiveDate;
use std::fmt;
/// A common type for toornament dates.
pub type Date = NaiveDate; | random_line_split | |
common.rs | use chrono::NaiveDate;
use std::fmt;
/// A common type for toornament dates.
pub type Date = NaiveDate;
macro_rules! enum_number {
($name:ident { $($variant:ident = $value:expr, )* }) => {
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum $name {... | {
/// Minimum team size
pub min: i64,
/// Maximum team size
pub max: i64,
}
enum_number!(MatchResultSimple {
Win = 1,
Draw = 2,
Loss = 3,
});
| TeamSize | identifier_name |
event.rs | #[cfg(not(any(test, rustdoc)))]
#[allow(unused_imports)]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
#[allow(unused_imports)]
use std::prelude::v1::*;
use crate::event::Event;
use crate::DRIVERS;
pub fn driver_event_handler(ev: Event) |
pub fn framework_event_handler(ev: Event) {
if ev.class!= "framework" {
return;
}
// assume subclass is framework name
if let Some(driver) = DRIVERS.get().find_framework_by_name(&ev.subclass) {
driver.get().handle_event(ev);
}
}
| {
if ev.class != "driver" {
return;
}
// assume the subclass is the driver ID, and convert it to a usize
let id = match ev.subclass.parse::<usize>() {
Ok(i) => i,
_ => return,
};
// find driver with given id
if let Some(driver) = DRIVERS.get().find_by_id(id) {
... | identifier_body |
event.rs | #[cfg(any(test, rustdoc))]
#[allow(unused_imports)]
use std::prelude::v1::*;
use crate::event::Event;
use crate::DRIVERS;
pub fn driver_event_handler(ev: Event) {
if ev.class!= "driver" {
return;
}
// assume the subclass is the driver ID, and convert it to a usize
let id = match ev.subclass.p... | #[cfg(not(any(test, rustdoc)))]
#[allow(unused_imports)]
use alloc::prelude::v1::*; | random_line_split | |
event.rs | #[cfg(not(any(test, rustdoc)))]
#[allow(unused_imports)]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
#[allow(unused_imports)]
use std::prelude::v1::*;
use crate::event::Event;
use crate::DRIVERS;
pub fn driver_event_handler(ev: Event) {
if ev.class!= "driver" {
return;
}
// assume the s... |
}
| {
driver.get().handle_event(ev);
} | conditional_block |
event.rs | #[cfg(not(any(test, rustdoc)))]
#[allow(unused_imports)]
use alloc::prelude::v1::*;
#[cfg(any(test, rustdoc))]
#[allow(unused_imports)]
use std::prelude::v1::*;
use crate::event::Event;
use crate::DRIVERS;
pub fn driver_event_handler(ev: Event) {
if ev.class!= "driver" {
return;
}
// assume the s... | (ev: Event) {
if ev.class!= "framework" {
return;
}
// assume subclass is framework name
if let Some(driver) = DRIVERS.get().find_framework_by_name(&ev.subclass) {
driver.get().handle_event(ev);
}
}
| framework_event_handler | identifier_name |
trait_inheritance_overloading_xc.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 ... |
}
impl Eq for MyInt {
fn eq(&self, other: &MyInt) -> bool { self.val == other.val }
fn ne(&self, other: &MyInt) -> bool {!self.eq(other) }
}
impl MyNum for MyInt;
fn mi(v: int) -> MyInt { MyInt { val: v } }
| { mi(self.val * other.val) } | identifier_body |
trait_inheritance_overloading_xc.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 ... | {
val: int
}
impl Add<MyInt, MyInt> for MyInt {
fn add(&self, other: &MyInt) -> MyInt { mi(self.val + other.val) }
}
impl Sub<MyInt, MyInt> for MyInt {
fn sub(&self, other: &MyInt) -> MyInt { mi(self.val - other.val) }
}
impl Mul<MyInt, MyInt> for MyInt {
fn mul(&self, other: &MyInt) -> MyInt { mi(s... | MyInt | identifier_name |
trait_inheritance_overloading_xc.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | random_line_split | |
cors.rs | use rocket::{Request, Response};
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::{Header, ContentType, Method};
use std::io::Cursor;
pub struct CORS();
impl Fairing for CORS {
fn info(&self) -> Info |
fn on_response(&self, request: &Request, response: &mut Response) {
if request.method() == Method::Options || response.content_type() == Some(ContentType::JSON) {
response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, ... | {
Info {
name: "Add CORS headers to requests",
kind: Kind::Response
}
} | identifier_body |
cors.rs | use rocket::{Request, Response};
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::{Header, ContentType, Method};
use std::io::Cursor;
pub struct CORS();
impl Fairing for CORS {
fn info(&self) -> Info {
Info {
name: "Add CORS headers to requests",
kind: Kind::Response
}
}
fn on_response(&sel... |
if request.method() == Method::Options {
response.set_header(ContentType::Plain);
response.set_sized_body(Cursor::new(""));
}
}
}
| {
response.set_header(Header::new("Access-Control-Allow-Origin", "*"));
response.set_header(Header::new("Access-Control-Allow-Methods", "POST, GET, OPTIONS"));
response.set_header(Header::new("Access-Control-Allow-Headers", "Content-Type"));
response.set_header(Header::new("Access-Control-Allow-Credentials"... | conditional_block |
cors.rs | use rocket::{Request, Response};
use rocket::fairing::{Fairing, Info, Kind}; | use rocket::http::{Header, ContentType, Method};
use std::io::Cursor;
pub struct CORS();
impl Fairing for CORS {
fn info(&self) -> Info {
Info {
name: "Add CORS headers to requests",
kind: Kind::Response
}
}
fn on_response(&self, request: &Request, response: &mut Response) {
if request.method() == Met... | random_line_split | |
cors.rs | use rocket::{Request, Response};
use rocket::fairing::{Fairing, Info, Kind};
use rocket::http::{Header, ContentType, Method};
use std::io::Cursor;
pub struct CORS();
impl Fairing for CORS {
fn | (&self) -> Info {
Info {
name: "Add CORS headers to requests",
kind: Kind::Response
}
}
fn on_response(&self, request: &Request, response: &mut Response) {
if request.method() == Method::Options || response.content_type() == Some(ContentType::JSON) {
response.set_header(Header::new("Access-Control-All... | info | identifier_name |
unwind-rec2.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 build2() -> Vec<int> {
panic!();
}
struct Blk { node: Vec<int>, span: Vec<int> }
fn main() {
let _blk = Blk {
node: build1(),
span: build2()
};
}
| {
vec!(0,0,0,0,0,0,0)
} | identifier_body |
unwind-rec2.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 ... | () -> Vec<int> {
panic!();
}
struct Blk { node: Vec<int>, span: Vec<int> }
fn main() {
let _blk = Blk {
node: build1(),
span: build2()
};
}
| build2 | identifier_name |
unwind-rec2.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 ... | struct Blk { node: Vec<int>, span: Vec<int> }
fn main() {
let _blk = Blk {
node: build1(),
span: build2()
};
} | fn build2() -> Vec<int> {
panic!();
}
| random_line_split |
regexp.rs | use std::borrow::ToOwned;
use std::collections::HashMap;
use regex::Regex;
use url::percent_encoding;
/// A route `Expression` is a regular expression compiled from a
/// "template string" in which portions of a URL path are bound to
/// named groupings denoted by curly braces.
///
/// This expression can then be matc... |
#[test]
fn test_template_extractor_values() {
let template = "/foo/{bar:pat}";
match extract_segments(template) {
Ok(meta_segment) => {
let (_, ref segment) = meta_segment[0];
assert!("bar:pat" == &segment[..]);
},
Err(msg) => { panic!("Error while extracting segments {}", msg); },
}
}
| {
// tests that a pattern w/ no extractable parameters
// can still be matched...
let template = Expression::from_template("/foo/bar").unwrap();
assert!(template.is_match("/foo/bar") == true);
assert!(template.is_match("/baz/qux") == false);
} | identifier_body |
regexp.rs | use std::borrow::ToOwned;
use std::collections::HashMap;
use regex::Regex;
use url::percent_encoding;
/// A route `Expression` is a regular expression compiled from a
/// "template string" in which portions of a URL path are bound to
/// named groupings denoted by curly braces.
///
/// This expression can then be matc... | ,
None => { break; },
}
}
if brace_count == 0 {
return Ok(segments);
} else {
return Err("missing closing brace in route pattern?");
}
}
//
// tests
//
// test creation of a template
#[test]
fn test_build_template() {
match Expression::from_template("/{foo}/{bar}") {
Err(e) => { panic!("{}", e); },... | {
input_buf = &input_buf[1..]; // move slice forward 1 char.
match token {
'{' => { brace_count += 1; continue; },
'}' => {
brace_count -= 1;
segments.push((segment_text.to_owned(),
param_text.to_owned()));
param_text = String::new();
segment_text = Stri... | conditional_block |
regexp.rs | use std::borrow::ToOwned;
use std::collections::HashMap;
use regex::Regex;
use url::percent_encoding;
/// A route `Expression` is a regular expression compiled from a
/// "template string" in which portions of a URL path are bound to
/// named groupings denoted by curly braces.
///
/// This expression can then be matc... | Some(captures) => {
for idx in 0..self.names.len() {
if let Some(binding) = captures.at(idx+1) {
// TODO: do we really want urlencoding in here?
// TODO: decode utf8 lossy? since this is a middleware it's not
// clear that there's... | random_line_split | |
regexp.rs | use std::borrow::ToOwned;
use std::collections::HashMap;
use regex::Regex;
use url::percent_encoding;
/// A route `Expression` is a regular expression compiled from a
/// "template string" in which portions of a URL path are bound to
/// named groupings denoted by curly braces.
///
/// This expression can then be matc... | (&self, path: &str) -> HashMap<String, String> {
let mut results = HashMap::new();
let captures = self.regex.captures(path);
// iterates over our list of named parameters and extracts
// the corresponding capture group from the regex.
//
// the captures are offset by 1 because the first match
// is th... | map_path | identifier_name |
received_mint.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account_address::AccountAddress;
use anyhow::Result;
use move_core_types::{
identifier::{IdentStr, Identifier},
move_resource::MoveResource,
};
use serde::{Deserialize, Serialize};
/// Struct that represents a Recei... |
/// Return the address who received the mint
pub fn destination_address(&self) -> AccountAddress {
self.destination_address
}
/// Return the code for the currency that was minted
pub fn currency_code(&self) -> &IdentStr {
&self.currency_code
}
pub fn try_from_bytes(bytes:... | {
self.amount
} | identifier_body |
received_mint.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account_address::AccountAddress;
use anyhow::Result;
use move_core_types::{
identifier::{IdentStr, Identifier},
move_resource::MoveResource,
};
use serde::{Deserialize, Serialize};
/// Struct that represents a Recei... |
/// Return the code for the currency that was minted
pub fn currency_code(&self) -> &IdentStr {
&self.currency_code
}
pub fn try_from_bytes(bytes: &[u8]) -> Result<Self> {
bcs::from_bytes(bytes).map_err(Into::into)
}
}
impl MoveResource for ReceivedMintEvent {
const MODULE_NAM... | pub fn destination_address(&self) -> AccountAddress {
self.destination_address
} | random_line_split |
received_mint.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account_address::AccountAddress;
use anyhow::Result;
use move_core_types::{
identifier::{IdentStr, Identifier},
move_resource::MoveResource,
};
use serde::{Deserialize, Serialize};
/// Struct that represents a Recei... | (&self) -> u64 {
self.amount
}
/// Return the address who received the mint
pub fn destination_address(&self) -> AccountAddress {
self.destination_address
}
/// Return the code for the currency that was minted
pub fn currency_code(&self) -> &IdentStr {
&self.currency_co... | amount | identifier_name |
p004.rs | fn | (){
println!("Euler Problem #4");
println!("Problem\tFind the largest palindrome made from the product of two 3-digit numbers");
println!("Solution: {}", largest_palendrome(100, 999));
}
fn largest_palendrome(min : i32, max : i32) -> i32 {
let mut solution = 0;
for a in std::iter::range_step_inclus... | main | identifier_name |
p004.rs | fn main(){
println!("Euler Problem #4");
println!("Problem\tFind the largest palindrome made from the product of two 3-digit numbers");
println!("Solution: {}", largest_palendrome(100, 999));
}
fn largest_palendrome(min : i32, max : i32) -> i32 {
let mut solution = 0; | for b in std::iter::range_step_inclusive(max, a, -1){
let c = a*b;
if c <= solution {break}
if is_palendrome(c) {solution = c}
}
}
return solution;
}
fn is_palendrome(a : i32) -> bool{
let mut y = 0i32;
let mut x = a;
while x > 0 {
y = y*... | for a in std::iter::range_step_inclusive(max, min, -1){ | random_line_split |
p004.rs | fn main(){
println!("Euler Problem #4");
println!("Problem\tFind the largest palindrome made from the product of two 3-digit numbers");
println!("Solution: {}", largest_palendrome(100, 999));
}
fn largest_palendrome(min : i32, max : i32) -> i32 {
let mut solution = 0;
for a in std::iter::range_step... |
if is_palendrome(c) {solution = c}
}
}
return solution;
}
fn is_palendrome(a : i32) -> bool{
let mut y = 0i32;
let mut x = a;
while x > 0 {
y = y*10 + x%10;
x /= 10;
}
return a==y
}
| {break} | conditional_block |
p004.rs | fn main() |
fn largest_palendrome(min : i32, max : i32) -> i32 {
let mut solution = 0;
for a in std::iter::range_step_inclusive(max, min, -1){
for b in std::iter::range_step_inclusive(max, a, -1){
let c = a*b;
if c <= solution {break}
if is_palendrome(c) {solution = c}
... | {
println!("Euler Problem #4");
println!("Problem\tFind the largest palindrome made from the product of two 3-digit numbers");
println!("Solution: {}", largest_palendrome(100, 999));
} | identifier_body |
36.rs | /* Problem 36: Double-base palindromes
*
* The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
*
* Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
*
* (Please note that the palindromic number, in either base, may not include leading zeros.... |
}
impl NumberFormatter for Decimal {
fn format(number: u32, buffer: &mut String) {
write!(buffer, "{}", number).unwrap();
}
}
fn main() {
let mut b1 = String::with_capacity(50);
let mut b2 = String::with_capacity(50);
let result: u32 = (1..1_000_000)
.filter(|number| is_palindrome... | {
write!(buffer, "{:b}", number).unwrap();
} | identifier_body |
36.rs | /* Problem 36: Double-base palindromes
*
* The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
*
* Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
*
* (Please note that the palindromic number, in either base, may not include leading zeros.... | struct Binary;
struct Decimal;
impl NumberFormatter for Binary {
fn format(number: u32, buffer: &mut String) {
write!(buffer, "{:b}", number).unwrap();
}
}
impl NumberFormatter for Decimal {
fn format(number: u32, buffer: &mut String) {
write!(buffer, "{}", number).unwrap();
}
}
fn ma... | random_line_split | |
36.rs | /* Problem 36: Double-base palindromes
*
* The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.
*
* Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.
*
* (Please note that the palindromic number, in either base, may not include leading zeros.... | (number: u32, buffer: &mut String) {
write!(buffer, "{}", number).unwrap();
}
}
fn main() {
let mut b1 = String::with_capacity(50);
let mut b2 = String::with_capacity(50);
let result: u32 = (1..1_000_000)
.filter(|number| is_palindrome::<Decimal>(*number, &mut b1))
.filter(|numbe... | format | identifier_name |
htmllielement.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::HTMLLIElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLLIElemen... |
}
| {
let element = HTMLLIElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLLIElementBinding::Wrap)
} | identifier_body |
htmllielement.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::HTMLLIElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLLIElemen... | HTMLLIElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLLIElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: JSRef<Document>) -> Tempora... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.