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 |
|---|---|---|---|---|
content.rs | #![stable]
use libc;
use std;
/// Opaque struct which holds a reference to the underlying Clutter object.
#[repr(C)]
pub struct ContentRef {
opaque: *mut libc::c_void
}
/// Delegate for painting the content of an actor
///
/// Content is an interface to implement types responsible for painting the
/// content of a... | (&mut self) {
unsafe {
clutter_content_invalidate(self.as_content());
}
}
}
impl Content for ContentRef {
fn as_content(&self) -> *mut libc::c_void {
return self.opaque;
}
}
extern {
fn clutter_content_get_preferred_size(self_value: *mut libc::c_void, width: *mut f32, height: *mut f32) -> i3... | invalidate | identifier_name |
content.rs | #![stable]
use libc;
use std;
/// Opaque struct which holds a reference to the underlying Clutter object.
#[repr(C)]
pub struct ContentRef {
opaque: *mut libc::c_void
}
/// Delegate for painting the content of an actor
///
/// Content is an interface to implement types responsible for painting the
/// content of a... |
/// Invalidates a Content.
///
/// This function should be called by Content implementations when they change
/// the way the content should be painted regardless of the actor state.
///
/// _Since 1.10_
fn invalidate(&mut self) {
unsafe {
clutter_content_invalidate(self.as_content());
}
... | {
unsafe {
let mut width:f32 = std::intrinsics::init();
let mut height:f32 = std::intrinsics::init();
let foreign_result = clutter_content_get_preferred_size(self.as_content(), &mut width, &mut height);
return (foreign_result != 0, width, height);
}
} | identifier_body |
issue-643-inner-struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub const fn new() -> Self {
__IncompleteArrayFie... | (&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_str("__IncompleteArrayField")
}
}
#[repr(C)]
#[derive(Debug)]
pub struct rte_ring {
pub memzone: *mut rte_memzone,
pub prod: rte_ring_prod,
pub cons: rte_ring_cons,
pub ring: __IncompleteArrayField<*mut ::std::os:... | fmt | identifier_name |
issue-643-inner-struct.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub const fn new() -> Self {
__IncompleteArrayFie... | &(*(::std::ptr::null::<rte_ring_cons>())).sc_dequeue as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rte_ring_cons),
"::",
stringify!(sc_dequeue)
)
);
}
#[test]
fn bindgen_test_layout... | );
assert_eq!(
unsafe { | random_line_split |
challenge36.rs | use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use srp::client::Client;
use srp::server::ClientHandler;
use srp::server::Server;
use crate::errors::*;
#[allow(clippy::type_complexity)]
pub fn start_server<T: ClientHandler>(
mut server: T,
port: u16,... | (port: u16, tx: &Sender<u8>) -> Result<()> {
// Ugly hack for shutting down the server
tx.send(1)?;
let stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
stream.shutdown(Shutdown:... | shutdown_server | identifier_name |
challenge36.rs | use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use srp::client::Client;
use srp::server::ClientHandler;
use srp::server::Server;
use crate::errors::*;
#[allow(clippy::type_complexity)]
pub fn start_server<T: ClientHandler>(
mut server: T,
port: u16,... |
pub fn connect_and_execute(port: u16, action: impl Fn(&mut TcpStream) -> Result<()>) -> Result<()> {
let mut stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
action(&mut stream)?;
s... | {
// Ugly hack for shutting down the server
tx.send(1)?;
let stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
stream.shutdown(Shutdown::Both)?;
Ok(())
} | identifier_body |
challenge36.rs | use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use srp::client::Client;
use srp::server::ClientHandler;
use srp::server::Server;
use crate::errors::*;
#[allow(clippy::type_complexity)]
pub fn start_server<T: ClientHandler>(
mut server: T,
port: u16,... | pub fn run() -> Result<()> {
let port: u16 = 8080;
let (tx, join_handle) = start_server(Server::default(), port)?;
let user_name = b"foo";
let password = b"baz";
let client = Client::new(user_name.to_vec(), password.to_vec());
connect_and_execute(port, |stream| client.register(stream))?;
c... | }
| random_line_split |
fdt.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use arch::android::create_android_fdt;
use arch::fdt::{Error, FdtWriter};
use data_model::DataInit;
use std::fs::File;
use std::mem;
use vm_memory::{Gu... | (
fdt_max_size: usize,
guest_mem: &GuestMemory,
fdt_load_offset: u64,
android_fstab: File,
) -> Result<usize, Error> {
// Reserve space for the setup_data
let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>();
let mut fdt = FdtWriter::new(&[]);
// The whole thing is put into ... | create_fdt | identifier_name |
fdt.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use arch::android::create_android_fdt;
use arch::fdt::{Error, FdtWriter};
use data_model::DataInit;
use std::fs::File;
use std::mem;
use vm_memory::{Gu... | // Reserve space for the setup_data
let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>();
let mut fdt = FdtWriter::new(&[]);
// The whole thing is put into one giant node with some top level properties
let root_node = fdt.begin_node("")?;
create_android_fdt(&mut fdt, android_fstab)?... | fdt_load_offset: u64,
android_fstab: File,
) -> Result<usize, Error> { | random_line_split |
fdt.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use arch::android::create_android_fdt;
use arch::fdt::{Error, FdtWriter};
use data_model::DataInit;
use std::fs::File;
use std::mem;
use vm_memory::{Gu... |
Ok(fdt_data_size)
}
| {
return Err(Error::FdtGuestMemoryWriteError);
} | conditional_block |
fdt.rs | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use arch::android::create_android_fdt;
use arch::fdt::{Error, FdtWriter};
use data_model::DataInit;
use std::fs::File;
use std::mem;
use vm_memory::{Gu... | len: fdt_data_size as u32,
};
assert!(fdt_data_size as u64 <= X86_64_FDT_MAX_SIZE);
let fdt_address = GuestAddress(fdt_load_offset);
guest_mem
.checked_offset(fdt_address, fdt_data_size as u64)
.ok_or(Error::FdtGuestMemoryWriteError)?;
guest_mem
.write_obj_at_addr(hdr,... | {
// Reserve space for the setup_data
let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>();
let mut fdt = FdtWriter::new(&[]);
// The whole thing is put into one giant node with some top level properties
let root_node = fdt.begin_node("")?;
create_android_fdt(&mut fdt, android_fstab... | identifier_body |
lib.rs | //! Watchexec: the library
//!
//! This is the library version of the CLI tool [watchexec]. The tool is
//! implemented with this library, but the purpose of the watchexec project is
//! to deliver the CLI tool, instead of focusing on the library interface first
//! and foremost. **For this reason, semver guarantees do... | pub use cli::{Args, ArgsBuilder};
pub use run::{run, watch, Handler}; | mod watcher;
| random_line_split |
notify.rs | use notify_rust::{Notification, NotificationHint, NotificationUrgency};
use rusthub::notifications;
use std::process::Command;
use std::thread;
use std::path::Path;
const APP_NAME: &'static str = "gh-notify";
pub fn | (notification: ¬ifications::Notification) {
let subject = format!("{} - {}", notification.subject.subject_type, notification.repository.name);
let body = notification.subject.title.clone();
let url = notification.subject.url.clone();
let url = url.replace("api.", "").replace("repos/", "").replace("/p... | show_notification | identifier_name |
notify.rs | use notify_rust::{Notification, NotificationHint, NotificationUrgency};
use rusthub::notifications;
use std::process::Command;
use std::thread;
use std::path::Path;
const APP_NAME: &'static str = "gh-notify";
pub fn show_notification(notification: ¬ifications::Notification) {
let subject = format!("{} - {}", n... | }
).unwrap_or_else(|err| error!("While showing notification: {}", err));
});
}
pub fn open_link(url: &str) {
debug!("Opening browser link: {}", url);
let _ = Command::new("sh")
.arg("-c")
.arg(format!("xdg-open '{}'", url))
.output()
.expect("Failed to open w... | random_line_split | |
notify.rs | use notify_rust::{Notification, NotificationHint, NotificationUrgency};
use rusthub::notifications;
use std::process::Command;
use std::thread;
use std::path::Path;
const APP_NAME: &'static str = "gh-notify";
pub fn show_notification(notification: ¬ifications::Notification) {
let subject = format!("{} - {}", n... |
pub fn notify_action<F>(summary: &str, body: &str, button_text: &str, timeout: i32, action: F) -> Result<(), String> where F: FnOnce(&str) {
let icon = match Path::new("./icon.png").canonicalize() {
Ok(path) => path.to_string_lossy().into_owned(),
Err(_) => "clock".to_string()
};
let hand... | {
debug!("Opening browser link: {}", url);
let _ = Command::new("sh")
.arg("-c")
.arg(format!("xdg-open '{}'", url))
.output()
.expect("Failed to open web browser instance.");
} | identifier_body |
lint-group-plugin.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 ... | () { }
}
| pleaselintme | identifier_name |
lint-group-plugin.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // 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... | // file at the top-level directory of this distribution and at | random_line_split |
lint-group-plugin.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 ... | //~ WARNING item is named 'pleaselintme'
#[allow(lint_me)]
pub fn main() {
fn lintme() { }
fn pleaselintme() { }
}
| { } | identifier_body |
build.rs | extern crate gcc;
use std::env;
fn | () {
let mut cfg = gcc::Config::new();
if env::var("TARGET").unwrap().contains("windows") {
cfg.define("_WIN32", None);
cfg.define("BZ_EXPORT", None);
}
cfg.include("bzip2-1.0.6")
.define("BZ_NO_STDIO", None)
.file("bzip2-1.0.6/blocksort.c")
.file("bzip2-1.0.6/huffman... | main | identifier_name |
build.rs | extern crate gcc;
use std::env;
fn main() {
let mut cfg = gcc::Config::new();
if env::var("TARGET").unwrap().contains("windows") {
cfg.define("_WIN32", None);
cfg.define("BZ_EXPORT", None);
}
cfg.include("bzip2-1.0.6")
.define("BZ_NO_STDIO", None)
.file("bzip2-1.0.6/block... | .file("bzip2-1.0.6/decompress.c")
.file("bzip2-1.0.6/bzlib.c")
.compile("libbz2.a");
} | random_line_split | |
build.rs | extern crate gcc;
use std::env;
fn main() {
let mut cfg = gcc::Config::new();
if env::var("TARGET").unwrap().contains("windows") |
cfg.include("bzip2-1.0.6")
.define("BZ_NO_STDIO", None)
.file("bzip2-1.0.6/blocksort.c")
.file("bzip2-1.0.6/huffman.c")
.file("bzip2-1.0.6/crctable.c")
.file("bzip2-1.0.6/randtable.c")
.file("bzip2-1.0.6/compress.c")
.file("bzip2-1.0.6/decompress.c")
.file("bzip2-1.... | {
cfg.define("_WIN32", None);
cfg.define("BZ_EXPORT", None);
} | conditional_block |
build.rs | extern crate gcc;
use std::env;
fn main() | {
let mut cfg = gcc::Config::new();
if env::var("TARGET").unwrap().contains("windows") {
cfg.define("_WIN32", None);
cfg.define("BZ_EXPORT", None);
}
cfg.include("bzip2-1.0.6")
.define("BZ_NO_STDIO", None)
.file("bzip2-1.0.6/blocksort.c")
.file("bzip2-1.0.6/huffman... | identifier_body | |
data_store.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
loaded_data::runtime_types::Type,
values::{GlobalValue, Value},
};
use move_core_types::{account_address::AccountAddress, language_storage::ModuleId};
use vm::errors::{PartialVMResult, VMResult};
/// Provide an imp... | pub trait DataStore {
// ---
// StateStore operations
// ---
/// Try to load a resource from remote storage and create a corresponding GlobalValue
/// that is owned by the data store.
fn load_resource(
&mut self,
addr: AccountAddress,
ty: &Type,
) -> PartialVMResult<... | /// The `DataStore` is a generic concept that includes both data and events.
/// A default implementation of the `DataStore` is `TransactionDataCache` which provides
/// an in memory cache for a given transaction and the atomic transactional changes
/// proper of a script execution (transaction). | random_line_split |
lib.rs | // Copyright 2016 Mozilla Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | 1
}
});
}
fn init_logging() {
if env::var(LOGGING_ENV).is_ok() {
match env_logger::Builder::from_env(LOGGING_ENV).try_init() {
Ok(_) => (),
Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)),
}
}
}
| {
init_logging();
std::process::exit(match cmdline::parse() {
Ok(cmd) => match commands::run_command(cmd) {
Ok(s) => s,
Err(e) => {
eprintln!("sccache: error: {}", e);
for e in e.chain().skip(1) {
eprintln!("sccache: caused by: ... | identifier_body |
lib.rs | // Copyright 2016 Mozilla Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
});
}
fn init_logging() {
if env::var(LOGGING_ENV).is_ok() {
match env_logger::Builder::from_env(LOGGING_ENV).try_init() {
Ok(_) => (),
Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)),
}
}
}
| {
println!("sccache: {}", e);
for e in e.chain().skip(1) {
println!("sccache: caused by: {}", e);
}
cmdline::get_app().print_help().unwrap();
println!();
1
} | conditional_block |
lib.rs | // Copyright 2016 Mozilla Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | mod protocol;
pub mod server;
#[cfg(feature = "simple-s3")]
mod simples3;
#[doc(hidden)]
pub mod util;
use std::env;
const LOGGING_ENV: &str = "SCCACHE_LOG";
pub fn main() {
init_logging();
std::process::exit(match cmdline::parse() {
Ok(cmd) => match commands::run_command(cmd) {
Ok(s) => ... | pub mod config;
pub mod dist;
mod jobserver;
mod mock_command; | random_line_split |
lib.rs | // Copyright 2016 Mozilla Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | () {
if env::var(LOGGING_ENV).is_ok() {
match env_logger::Builder::from_env(LOGGING_ENV).try_init() {
Ok(_) => (),
Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)),
}
}
}
| init_logging | identifier_name |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod heartbeat;
mod lsp_notification_dispatch;
mod lsp_request_dispatch;
mod lsp_state;
mod lsp_state_resources;
use crate::{
c... | {
let notification = LSPNotificationDispatch::new(notification, lsp_state)
.on_notification_sync::<DidOpenTextDocument>(on_did_open_text_document)?
.on_notification_sync::<DidCloseTextDocument>(on_did_close_text_document)?
.on_notification_sync::<DidChangeTextDocument>(on_did_change_text_doc... | identifier_body | |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod heartbeat;
mod lsp_notification_dispatch;
mod lsp_request_dispatch;
mod lsp_state;
mod lsp_state_resources;
use crate::{
c... | <TPerfLogger: PerfLogger +'static>(
notification: lsp_server::Notification,
lsp_state: &mut LSPState<TPerfLogger>,
) -> Result<(), Option<LSPRuntimeError>> {
let notification = LSPNotificationDispatch::new(notification, lsp_state)
.on_notification_sync::<DidOpenTextDocument>(on_did_open_text_document... | dispatch_notification | identifier_name |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod heartbeat;
mod lsp_notification_dispatch;
mod lsp_request_dispatch;
mod lsp_state;
mod lsp_state_resources;
use crate::{
c... |
}
}
}
fn handle_request<TPerfLogger: PerfLogger +'static>(
lsp_state: &mut LSPState<TPerfLogger>,
request: lsp_server::Request,
sender: &Sender<Message>,
perf_logger: &Arc<TPerfLogger>,
) -> Result<(), SendError<Message>> {
debug!("request received {:?}", request);
let get_server_r... | {
panic!("Relay Language Server receiver error {:?}", error);
} | conditional_block |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod heartbeat;
mod lsp_notification_dispatch;
mod lsp_request_dispatch; | use crate::{
code_action::on_code_action,
completion::on_completion,
goto_definition::{
on_get_source_location_of_type_definition, on_goto_definition,
GetSourceLocationOfTypeDefinition,
},
graphql_tools::on_graphql_execute_query,
graphql_tools::GraphQLExecuteQuery,
hover::on_... | mod lsp_state;
mod lsp_state_resources;
| random_line_split |
wad.rs | use std::u8;
use nom::{self, IResult, Needed, le_u32};
use super::util::fixed_length_ascii;
use ::errors::{Result, nom_to_result};
use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType};
named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD")));
named!(pwad_tag<WADType>, value!(WADType::... | {
// FIXME ambiguous whether the error was from parsing the header or the entries
let header = nom_to_result("wad header", buf, wad_header(buf))?;
// TODO buf is not actually the right place here
let entries = nom_to_result("wad index", buf, wad_directory(buf, &header))?;
Ok(BareWAD{ buffer: buf, he... | identifier_body | |
wad.rs | use std::u8;
use nom::{self, IResult, Needed, le_u32};
use super::util::fixed_length_ascii;
use ::errors::{Result, nom_to_result};
use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType};
|
named!(wad_header<BareWADHeader>, do_parse!(
identification: return_error!(
nom::ErrorKind::Custom(1),
alt!(iwad_tag | pwad_tag)) >>
numlumps: le_u32 >>
infotableofs: le_u32 >>
(BareWADHeader{ identification, numlumps, infotableofs })
));
named!(wad_entry<BareWADDirectoryEntry>, dbg_d... | named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD")));
named!(pwad_tag<WADType>, value!(WADType::PWAD, tag!(b"PWAD"))); | random_line_split |
wad.rs | use std::u8;
use nom::{self, IResult, Needed, le_u32};
use super::util::fixed_length_ascii;
use ::errors::{Result, nom_to_result};
use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType};
named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD")));
named!(pwad_tag<WADType>, value!(WADType::... | <'a>(buf: &'a [u8], header: &BareWADHeader) -> IResult<&'a [u8], Vec<BareWADDirectoryEntry<'a>>> {
let lumpct = header.numlumps as usize;
let offset = header.infotableofs as usize;
// TODO can i unhardcode the size of a wad entry here?
let tablelen = lumpct * 16;
if buf.len() < offset + tablelen {
... | wad_directory | identifier_name |
wad.rs | use std::u8;
use nom::{self, IResult, Needed, le_u32};
use super::util::fixed_length_ascii;
use ::errors::{Result, nom_to_result};
use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType};
named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD")));
named!(pwad_tag<WADType>, value!(WADType::... |
let mut ret = Vec::with_capacity(lumpct);
let mut parse_from = &buf[offset..];
for _ in 0..lumpct {
let (leftovers, entry) = try_parse!(parse_from, wad_entry);
ret.push(entry);
parse_from = leftovers;
}
Ok((parse_from, ret))
}
// TODO problems to scan a wad map for:
// - ... | {
return Err(nom::Err::Incomplete(Needed::Size(tablelen)));
} | conditional_block |
mod.rs | try!(mkdir_recursive(&self.dirname()));
let mut file = try!(
fs::File::create(&self.path)
.with_err_msg(format!("Could not create file; path={}",
self.path.display())));
file.write_all(self.body.as_bytes())
.with_err_m... | (mut self, expected: i32) -> Execs {
self.expect_exit_code = Some(expected);
self
}
pub fn with_stdout_contains<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stdout_contains.push(expected.to_string());
self
}
pub fn with_stderr_contains<S: ToString>(mut sel... | with_status | identifier_name |
mod.rs | {
try!(mkdir_recursive(&self.dirname()));
let mut file = try!(
fs::File::create(&self.path)
.with_err_msg(format!("Could not create file; path={}",
self.path.display())));
file.write_all(self.body.as_bytes())
.with_er... | `{}`", diffs.connect("\n"),
String::from_utf8_lossy(extra)))
}
fn match_json(&self, expected: &Json, stdout: &[u8]) -> ham::MatchResult {
let stdout = match str::from_utf8(stdout) {
Err(..) => return Err("stdout was not utf8 encoded".... | other output:\n\ | random_line_split |
mod.rs | try!(mkdir_recursive(&self.dirname()));
let mut file = try!(
fs::File::create(&self.path)
.with_err_msg(format!("Could not create file; path={}",
self.path.display())));
file.write_all(self.body.as_bytes())
.with_err_m... |
}
pub fn shell_writes<T: fmt::Display>(string: T) -> ShellWrites {
ShellWrites { | {
let actual = String::from_utf8_lossy(actual);
let actual = actual.to_string();
ham::expect(actual == self.expected, actual)
} | identifier_body |
commands.rs | use std::string::String;
use regex::Regex;
use platform::EOL;
use REHolder;
pub fn show_help() -> String {
"This is help page.".to_string() + EOL.as_ref() +
"Or at leas will be....".as_ref()
}
pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String {
current_re.set(Regex::new(regex).unwrap())... | (input: &str, current_re: &REHolder) -> String {
if!current_re.re.is_match(input) {
return "Input does not match the pattern. ".to_string();
}
let mut output = String::new();
for (ind, cap) in current_re.re.captures_iter(input).enumerate() {
if ind > 0 {
output += format!("... | test_input | identifier_name |
commands.rs | use std::string::String;
use regex::Regex;
use platform::EOL;
use REHolder;
pub fn show_help() -> String {
"This is help page.".to_string() + EOL.as_ref() +
"Or at leas will be....".as_ref()
}
pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String {
current_re.set(Regex::new(regex).unwrap())... |
let mut output = String::new();
for (ind, cap) in current_re.re.captures_iter(input).enumerate() {
if ind > 0 {
output += format!("==========={}", EOL).as_ref();
}
output += format!(">>> Match #{}, capture groups: {}", ind + 1, EOL).as_ref();
for c_ind in 0..cap.le... | {
return "Input does not match the pattern. ".to_string();
} | conditional_block |
commands.rs | use std::string::String;
use regex::Regex;
use platform::EOL;
use REHolder;
pub fn show_help() -> String {
"This is help page.".to_string() + EOL.as_ref() + | current_re.set(Regex::new(regex).unwrap());
format!("Regex was set: {}\n", regex)
}
pub fn test_input(input: &str, current_re: &REHolder) -> String {
if!current_re.re.is_match(input) {
return "Input does not match the pattern. ".to_string();
}
let mut output = String::new();
for (ind,... | "Or at leas will be....".as_ref()
}
pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String { | random_line_split |
commands.rs | use std::string::String;
use regex::Regex;
use platform::EOL;
use REHolder;
pub fn show_help() -> String {
"This is help page.".to_string() + EOL.as_ref() +
"Or at leas will be....".as_ref()
}
pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String |
pub fn test_input(input: &str, current_re: &REHolder) -> String {
if!current_re.re.is_match(input) {
return "Input does not match the pattern. ".to_string();
}
let mut output = String::new();
for (ind, cap) in current_re.re.captures_iter(input).enumerate() {
if ind > 0 {
... | {
current_re.set(Regex::new(regex).unwrap());
format!("Regex was set: {}\n", regex)
} | identifier_body |
read_manifest.rs | use std::env;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE... | Options:
-h, --help Print this message
-v, --verbose Use verbose output
--manifest-path PATH Path to the manifest
--color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<Package>> {
debug!("executin... | Usage:
cargo read-manifest [options]
cargo read-manifest -h | --help
| random_line_split |
read_manifest.rs | use std::env;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE... | {
debug!("executing; cmd=cargo-read-manifest; args={:?}",
env::args().collect::<Vec<_>>());
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(options.flag_manifest_path, config.cwd()));
let mut source = try!(PathSou... | identifier_body | |
read_manifest.rs | use std::env;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct | {
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Print a JSON representation of a Cargo.toml manifest
Usage:
cargo read-manifest [options]
cargo read-manifest -h | --help
Options:
-h, --help Print this message
-v, --verbose ... | Options | identifier_name |
coreutils.rs | // This file is part of the uutils coreutils package.
//
// (c) Michael Gehring <mg@ebfe.org>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use clap::{App, Arg};
use clap_complete::Shell;
use std::cmp;
use std::ffi::OsStr;
use std::ffi... | ;
// 0th argument equals util name?
if let Some(util_os) = util_name {
fn not_found(util: &OsStr) ->! {
println!("{}: function/utility not found", util.maybe_quote());
process::exit(1);
}
let util = match util_os.to_str() {
Some(util) => util,
... | {
// unmatched binary name => regard as multi-binary container and advance argument list
uucore::set_utility_is_second_arg();
args.next()
} | conditional_block |
coreutils.rs | // This file is part of the uutils coreutils package.
//
// (c) Michael Gehring <mg@ebfe.org>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use clap::{App, Arg};
use clap_complete::Shell;
use std::cmp;
use std::ffi::OsStr;
use std::ffi... |
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
if util == "completion" {
gen_completions(args, &utils);
}
match utils.get(util) {
Some(&(uumain, _)) => {
process::exit(uum... | {
println!("{}: function/utility not found", util.maybe_quote());
process::exit(1);
} | identifier_body |
coreutils.rs | // This file is part of the uutils coreutils package.
//
// (c) Michael Gehring <mg@ebfe.org>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use clap::{App, Arg};
use clap_complete::Shell;
use std::cmp;
use std::ffi::OsStr; | use std::process;
use uucore::display::Quotable;
const VERSION: &str = env!("CARGO_PKG_VERSION");
include!(concat!(env!("OUT_DIR"), "/uutils_map.rs"));
fn usage<T>(utils: &UtilityMap<T>, name: &str) {
println!("{} {} (multi-call binary)\n", name, VERSION);
println!("Usage: {} [function [arguments...]]\n", na... | use std::ffi::OsString;
use std::io::{self, Write};
use std::path::{Path, PathBuf}; | random_line_split |
coreutils.rs | // This file is part of the uutils coreutils package.
//
// (c) Michael Gehring <mg@ebfe.org>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use clap::{App, Arg};
use clap_complete::Shell;
use std::cmp;
use std::ffi::OsStr;
use std::ffi... | () {
uucore::panic::mute_sigpipe_panic();
let utils = util_map();
let mut args = uucore::args_os();
let binary = binary_path(&mut args);
let binary_as_util = name(&binary);
// binary name equals util name?
if let Some(&(uumain, _)) = utils.get(binary_as_util) {
process::exit(uumai... | main | identifier_name |
packet.rs | // Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// ... | destination_port,
payload: vec![],
}
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = payload;
self
}
pub fn build(self) -> Vec<u8> {
let mut buf = BytesMut::new();
buf.put_u16(self.source_port);
buf.put_u16(... | impl TcpBuilder {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port, | random_line_split |
packet.rs | // Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// ... | () {
let source: Ipv4Addr = "10.10.10.10".parse().unwrap();
let destination: Ipv4Addr = "127.127.127.127".parse().unwrap();
let tcp = TcpBuilder::new(5555, 6666)
.payload(vec![0x41, 0x41, 0x41, 0x41, 0x41])
.build();
let builder = Ip4Builder::new()
.pro... | parse_ip_addr | identifier_name |
packet.rs | // Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// ... |
pub fn destination(mut self, addr: Ipv4Addr) -> Self {
self.dest_addr = addr;
self
}
pub fn ttl(mut self, ttl: u8) -> Self {
self.ttl = ttl;
self
}
pub fn protocol(mut self, protocol: Protocol) -> Self {
self.protocol = protocol;
self
}
pu... | {
self.source_addr = addr;
self
} | identifier_body |
packet.rs | // Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// ... | else {
result += pdu.get_u16() as u32;
}
if result > 0xffff {
result -= 0xffff;
}
}
return!result as u16;
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::pcap;
#[test]
fn parse_ip_addr() {
let source... | {
result += (pdu.get_u8() as u32) << 8;
} | conditional_block |
universal_fn_syntax_call.rs | pub fn universal_fn_syntax_call() {
println!("***Universal Function Syntax Call***");
one();
println!("");
}
trait Foo {
fn f(&self);
}
trait Bar {
fn f(&self);
}
struct Baz;
impl Foo for Baz {
fn f(&self) |
}
impl Bar for Baz {
fn f(&self) {
println!("Baz's implementation of bar.");
}
}
trait Foo2 {
fn foo() -> i32;
}
struct Bar2;
impl Bar2 {
fn foo() -> i32 {
20
}
}
impl Foo2 for Bar2 {
fn foo() -> i32 {
10
}
}
fn one() {
let b = Baz;
// b.f(); // can't c... | {
println!("Baz's implementation of foo.");
} | identifier_body |
universal_fn_syntax_call.rs | pub fn universal_fn_syntax_call() {
println!("***Universal Function Syntax Call***");
one();
println!("");
}
| fn f(&self);
}
trait Bar {
fn f(&self);
}
struct Baz;
impl Foo for Baz {
fn f(&self) {
println!("Baz's implementation of foo.");
}
}
impl Bar for Baz {
fn f(&self) {
println!("Baz's implementation of bar.");
}
}
trait Foo2 {
fn foo() -> i32;
}
struct Bar2;
impl Bar2 {
... | trait Foo { | random_line_split |
universal_fn_syntax_call.rs | pub fn universal_fn_syntax_call() {
println!("***Universal Function Syntax Call***");
one();
println!("");
}
trait Foo {
fn f(&self);
}
trait Bar {
fn f(&self);
}
struct Baz;
impl Foo for Baz {
fn f(&self) {
println!("Baz's implementation of foo.");
}
}
impl Bar for Baz {
... | () -> i32 {
10
}
}
fn one() {
let b = Baz;
// b.f(); // can't call because of disambiguity
Foo::f(&b); // same as f.b();
Bar::f(&b); // same as f.b();
// angle-bracket form
assert_eq!(10, <Bar2 as Foo2>::foo());
assert_eq!(20, Bar2::foo());
}
| foo | identifier_name |
basic_usage.rs | // Copyright 2015, Igor Shaula
// Licensed under the MIT License <LICENSE or
// http://opensource.org/licenses/MIT>. This file
// may not be copied, modified, or distributed
// except according to those terms.
extern crate winreg;
use std::io;
use std::path::Path;
use winreg::enums::*;
use winreg::RegKey;
fn main() ->... | let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let path = Path::new("Software").join("WinregRsExample1");
let (key, disp) = hkcu.create_subkey(&path)?;
match disp {
REG_CREATED_NEW_KEY => println!("A new key has been created"),
REG_OPENED_EXISTING_KEY => println!("An existing key has bee... | {
println!("Reading some system info...");
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?;
let pf: String = cur_ver.get_value("ProgramFilesDir")?;
let dp: String = cur_ver.get_value("DevicePath")?;
println!("ProgramF... | identifier_body |
basic_usage.rs | // Copyright 2015, Igor Shaula
// Licensed under the MIT License <LICENSE or
// http://opensource.org/licenses/MIT>. This file
// may not be copied, modified, or distributed
// except according to those terms.
extern crate winreg;
use std::io;
use std::path::Path;
use winreg::enums::*;
use winreg::RegKey;
fn main() ->... | let multi_sz_val: Vec<String> = key.get_value("TestMultiSZ")?;
key.delete_value("TestMultiSZ")?;
println!("TestMultiSZ = {:?}", multi_sz_val);
key.set_value("TestDWORD", &1_234_567_890u32)?;
let dword_val: u32 = key.get_value("TestDWORD")?;
println!("TestDWORD = {}", dword_val);
key.set_va... | key.delete_value("TestSZ")?;
println!("TestSZ = {}", sz_val);
key.set_value("TestMultiSZ", &vec!["written", "by", "Rust"])?; | random_line_split |
basic_usage.rs | // Copyright 2015, Igor Shaula
// Licensed under the MIT License <LICENSE or
// http://opensource.org/licenses/MIT>. This file
// may not be copied, modified, or distributed
// except according to those terms.
extern crate winreg;
use std::io;
use std::path::Path;
use winreg::enums::*;
use winreg::RegKey;
fn | () -> io::Result<()> {
println!("Reading some system info...");
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?;
let pf: String = cur_ver.get_value("ProgramFilesDir")?;
let dp: String = cur_ver.get_value("DevicePath")?;
... | main | identifier_name |
externalities.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | (&mut self, gas: &U256, value: &U256, code: &[u8]) -> ContractCreateResult {
// create new contract address
let address = contract_address(&self.origin_info.address, &self.state.nonce(&self.origin_info.address));
// prepare the params
let params = ActionParams {
code_address: address.clone(),
address: ad... | create | identifier_name |
externalities.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
}
/// Implementation of evm Externalities.
pub struct Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
state: &'a mut State,
env_info: &'a EnvInfo,
engine: &'a Engine,
vm_factory: &'a Factory,
depth: usize,
origin_info: OriginInfo,
substate: &'a mut Substate,
schedule: Schedule,
output: Outpu... | {
OriginInfo {
address: params.address.clone(),
origin: params.origin.clone(),
gas_price: params.gas_price,
value: match params.value {
ActionValue::Transfer(val) | ActionValue::Apparent(val) => val
}
}
} | identifier_body |
externalities.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | ,
}
}
fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> ContractCreateResult {
// create new contract address
let address = contract_address(&self.origin_info.address, &self.state.nonce(&self.origin_info.address));
// prepare the params
let params = ActionParams {
code_address: address.clo... | {
trace!("ext: blockhash({}) -> null self.env_info.number={}\n", number, self.env_info.number);
H256::zero()
} | conditional_block |
externalities.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | true => Err(evm::Error::OutOfGas),
false => Ok(*gas)
}
}
handle_copy(copy);
let mut code = vec![];
code.extend_from_slice(data);
self.state.init_code(&self.origin_info.address, code);
Ok(*gas - return_cost)
}
}
}
fn log(&mut self, topics: Vec<H256>, data: &[u8]) {
u... | random_line_split | |
default.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
StaticEnum(..) => {
cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
// let compilation continue
cx.expr_usize(trait_span, 0)
}
_ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")
};
}
| {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
... | conditional_block |
default.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | attributes: attrs,
is_unsafe: false,
combine_substructure: combine_substructure(Box::new(|a, b, c| {
default_substructure(a, b, c)
}))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem,... | explicit_self: None,
args: Vec::new(),
ret_ty: Self_, | random_line_split |
default.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | }))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("de... | {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: path_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: Lifetim... | identifier_body |
default.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec... | default_substructure | identifier_name |
gecko.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/. */
//! Specified types for legacy Gecko-only properties.
use crate::parser::{Parse, ParserContext};
use crate::valu... | <W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
// We cannot use the ToCss impl of Rect, because that would
// merge items when they are equal. We want to list them all.
let mut writer = SequenceWriter::new(dest, " ");
let rect = &self.0;
... | to_css | identifier_name |
gecko.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/. */
//! Specified types for legacy Gecko-only properties.
use crate::parser::{Parse, ParserContext};
use crate::valu... | /// <https://w3c.github.io/IntersectionObserver/#parse-a-root-margin>
#[repr(transparent)]
pub struct IntersectionObserverRootMargin(pub Rect<LengthPercentage>);
impl Parse for IntersectionObserverRootMargin {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Se... | /// | random_line_split |
directconnect.rs | #![cfg(feature = "directconnect")]
extern crate rusoto;
use rusoto::directconnect::{DirectConnectClient, DescribeConnectionsRequest, DescribeConnectionsError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_describe_connections() {
let credentials = DefaultCre... |
#[test]
fn should_describe_locations() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
client.describe_locations().unwrap();
}
#[test]
fn should_describe_virtual_gateways() {
let crede... | {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeConnectionsRequest {
connection_id: Some("invalid".to_string())
};
match client.describe_connections(&re... | identifier_body |
directconnect.rs | #![cfg(feature = "directconnect")]
extern crate rusoto;
use rusoto::directconnect::{DirectConnectClient, DescribeConnectionsRequest, DescribeConnectionsError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_describe_connections() {
let credentials = DefaultCre... | () {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
client.describe_virtual_gateways().unwrap();
}
| should_describe_virtual_gateways | identifier_name |
directconnect.rs | #![cfg(feature = "directconnect")]
extern crate rusoto;
use rusoto::directconnect::{DirectConnectClient, DescribeConnectionsRequest, DescribeConnectionsError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_describe_connections() {
let credentials = DefaultCre... | let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeConnectionsRequest {
connection_id: Some("invalid".to_string())
};
match client.describe_connections(&requ... | #[test]
fn should_fail_gracefully() { | random_line_split |
thread.rs | use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::os::windows::io::{AsRawHandle, FromRawHandle};
use crate::ptr;
use crate::sys::c;
use crate::sys::handle::Handle;
use crate::sys::stack_overflow;
use crate::time::Duration;
use libc::c_void;
use super::to_u16s;
pub const DEFAULT_MIN_STACK_... | (main: *mut c_void) -> c::DWORD {
unsafe {
// Next, set up our stack overflow handler which may get triggered if we run
// out of stack.
let _handler = stack_overflow::Handler::new();
// Finally, let's run some code.
Box::from_r... | thread_start | identifier_name |
thread.rs | use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::os::windows::io::{AsRawHandle, FromRawHandle};
use crate::ptr;
use crate::sys::c;
use crate::sys::handle::Handle;
use crate::sys::stack_overflow;
use crate::time::Duration;
use libc::c_void;
use super::to_u16s;
pub const DEFAULT_MIN_STACK_... | }
}
pub fn yield_now() {
// This function will return 0 if there are no other threads to execute,
// but this also means that the yield was useless so this isn't really a
// case that needs to be worried about.
unsafe {
c::SwitchToThread();
}
}
... | let rc = unsafe { c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE) };
if rc == c::WAIT_FAILED {
panic!("failed to join on thread: {}", io::Error::last_os_error()); | random_line_split |
thread.rs | use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::os::windows::io::{AsRawHandle, FromRawHandle};
use crate::ptr;
use crate::sys::c;
use crate::sys::handle::Handle;
use crate::sys::stack_overflow;
use crate::time::Duration;
use libc::c_void;
use super::to_u16s;
pub const DEFAULT_MIN_STACK_... |
}
pub fn yield_now() {
// This function will return 0 if there are no other threads to execute,
// but this also means that the yield was useless so this isn't really a
// case that needs to be worried about.
unsafe {
c::SwitchToThread();
}
}
pub fn... | {
panic!("failed to join on thread: {}", io::Error::last_os_error());
} | conditional_block |
thread.rs | use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::os::windows::io::{AsRawHandle, FromRawHandle};
use crate::ptr;
use crate::sys::c;
use crate::sys::handle::Handle;
use crate::sys::stack_overflow;
use crate::time::Duration;
use libc::c_void;
use super::to_u16s;
pub const DEFAULT_MIN_STACK_... |
pub fn sleep(dur: Duration) {
unsafe { c::Sleep(super::dur2timeout(dur)) }
}
pub fn handle(&self) -> &Handle {
&self.handle
}
pub fn into_handle(self) -> Handle {
self.handle
}
}
pub fn available_parallelism() -> io::Result<NonZeroUsize> {
let res = unsafe {
... | {
// This function will return 0 if there are no other threads to execute,
// but this also means that the yield was useless so this isn't really a
// case that needs to be worried about.
unsafe {
c::SwitchToThread();
}
} | identifier_body |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... | (localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLObjectElement> {
let element = HTMLObjectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap)
}
}
trait ProcessDataUR... | new | identifier_name |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... |
}
trait ProcessDataURL {
fn process_data_url(&self);
}
impl<'a> ProcessDataURL for &'a HTMLObjectElement {
// Makes the local `data` member match the status of the `data` attribute and starts
/// prefetching the image. This method must be called after `data` is changed.
fn process_data_url(&self) {
... | {
let element = HTMLObjectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap)
} | identifier_body |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementB... | ,
_ => {},
}
}
}
impl FormControl for HTMLObjectElement {}
| {
if let AttributeMutation::Set(_) = mutation {
self.process_data_url();
}
} | conditional_block |
simple.rs | use std::env;
use std::io;
use std::io::{Error, Write};
use std::path::Path;
use std::sync::Arc;
use log::error;
use petgraph::Graph;
use tempdir::TempDir;
use crate::clang::compiler::ClangCompiler;
use crate::cluster::client::RemoteCompiler;
use crate::compiler::*;
use crate::config::Config;
use crate::vs::compiler:... |
pub fn simple_compile<C, F>(exec: &str, factory: F) -> i32
where
C: Compiler,
F: FnOnce(&Config) -> Result<C, Error>,
{
let config = match Config::new() {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't load configuration {}", e);
return 501;
}
};
... | {
TempDir::new("octobuild").map(Arc::new)
} | identifier_body |
simple.rs | use std::env;
use std::io;
use std::io::{Error, Write};
use std::path::Path;
use std::sync::Arc;
use log::error;
use petgraph::Graph;
use tempdir::TempDir;
use crate::clang::compiler::ClangCompiler;
use crate::cluster::client::RemoteCompiler;
use crate::compiler::*;
use crate::config::Config;
use crate::vs::compiler:... | <C>(
config: &Config,
state: &SharedState,
exec: &str,
compiler: C,
) -> Result<Option<i32>, Error>
where
C: Compiler,
{
let args: Vec<String> = env::args().collect();
let command_info = CommandInfo::simple(Path::new(exec));
let remote = RemoteCompiler::new(&config.coordinator, compiler)... | compile | identifier_name |
simple.rs | use std::env;
use std::io;
use std::io::{Error, Write};
use std::path::Path;
use std::sync::Arc;
use log::error;
use petgraph::Graph;
use tempdir::TempDir;
use crate::clang::compiler::ClangCompiler;
use crate::cluster::client::RemoteCompiler;
use crate::compiler::*;
use crate::config::Config;
use crate::vs::compiler:... | let args: Vec<String> = env::args().collect();
let command_info = CommandInfo::simple(Path::new(exec));
let remote = RemoteCompiler::new(&config.coordinator, compiler);
let actions = BuildAction::create_tasks(&remote, command_info, &args[1..], exec);
let mut build_graph: BuildGraph = Graph::new();
... | C: Compiler,
{ | random_line_split |
nodemap.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::Range;
use std::path::Path;
use anyhow::Result;
use indexedlog::{
log::{self, IndexOutput, Log},
DefaultOpenOptions,
}... | }
let second = second.pop().unwrap();
Ok((Node::from_slice(&first)?, Node::from_slice(&second)?))
}
Err(e) => Err(e.into()),
}
});
Ok(Box::new(iter))
}
}
#[cfg(test)]
mod tests {
use super:... | {
let iter = self.log.iter().map(move |entry| {
match entry {
Ok(data) => {
let mut first = self.log.index_func(0, &data)?;
if first.len() != 1 {
return Err(NodeMapError(format!(
"invalid inde... | identifier_body |
nodemap.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::Range;
use std::path::Path;
use anyhow::Result;
use indexedlog::{
log::{self, IndexOutput, Log},
DefaultOpenOptions,
}... |
let second = second.pop().unwrap();
Ok((Node::from_slice(&first)?, Node::from_slice(&second)?))
}
Err(e) => Err(e.into()),
}
});
Ok(Box::new(iter))
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck... | {
return Err(NodeMapError(format!(
"invalid index 2 keys in {:?}",
self.log.dir
))
.into());
} | conditional_block |
nodemap.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::Range; | log::{self, IndexOutput, Log},
DefaultOpenOptions,
};
use thiserror::Error;
use types::errors::KeyError;
use types::node::Node;
#[derive(Debug, Error)]
#[error("Node Map Error: {0:?}")]
struct NodeMapError(String);
impl From<NodeMapError> for KeyError {
fn from(err: NodeMapError) -> Self {
KeyErro... | use std::path::Path;
use anyhow::Result;
use indexedlog::{ | random_line_split |
nodemap.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::Range;
use std::path::Path;
use anyhow::Result;
use indexedlog::{
log::{self, IndexOutput, Log},
DefaultOpenOptions,
}... | {
log: Log,
}
impl DefaultOpenOptions<log::OpenOptions> for NodeMap {
fn default_open_options() -> log::OpenOptions {
let first_index = |_data: &[u8]| vec![IndexOutput::Reference(0..20)];
let second_index = |_data: &[u8]| vec![IndexOutput::Reference(20..40)];
log::OpenOptions::new()
... | NodeMap | identifier_name |
domparser.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::DOMParserBinding;
use dom::bindings::utils::{CacheableWrapper, WrapperCache};
use dom:... | (&mut self) -> &mut WrapperCache {
unsafe { cast::transmute(&self.wrapper) }
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
DOMParserBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for DOMParser {
f... | get_wrappercache | identifier_name |
domparser.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::DOMParserBinding;
use dom::bindings::utils::{CacheableWrapper, WrapperCache};
use dom:... | else {
unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) };
return 1;
}
}
}
| {
return 0;
} | conditional_block |
domparser.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::DOMParserBinding;
use dom::bindings::utils::{CacheableWrapper, WrapperCache};
use dom:... | let obj = self.wrap_object_shared(cx, scope);
if obj.is_null() {
return 0;
} else {
unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) };
return 1;
}
}
} | fail!(~"nyi")
}
fn wrap_shared(@mut self, cx: *JSContext, scope: *JSObject, vp: *mut JSVal) -> i32 { | random_line_split |
domparser.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::DOMParserBinding;
use dom::bindings::utils::{CacheableWrapper, WrapperCache};
use dom:... |
}
| {
let obj = self.wrap_object_shared(cx, scope);
if obj.is_null() {
return 0;
} else {
unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) };
return 1;
}
} | identifier_body |
issue-2895.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!(mem::size_of::<Cat>(), 4 as uint);
assert_eq!(mem::size_of::<Kitty>(), 8 as uint);
} | identifier_body | |
issue-2895.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 ... | (&mut self) {}
}
#[cfg(target_arch = "x86_64")]
pub fn main() {
assert_eq!(mem::size_of::<Cat>(), 8 as uint);
assert_eq!(mem::size_of::<Kitty>(), 16 as uint);
}
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
pub fn main() {
assert_eq!(mem::size_of::<Cat>(), 4 as uint);
assert_eq!(mem::size_of::... | drop | identifier_name |
issue-2895.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 Drop for Kitty {
fn drop(&mut self) {}
}
#[cfg(target_arch = "x86_64")]
pub fn main() {
assert_eq!(mem::size_of::<Cat>(), 8 as uint);
assert_eq!(mem::size_of::<Kitty>(), 16 as uint);
}
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
pub fn main() {
assert_eq!(mem::size_of::<Cat>(), 4 as ui... |
struct Kitty {
x: int,
} | random_line_split |
keywords.rs | use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case};
use nom::combinator::peek;
use nom::sequence::terminated;
use nom::IResult;
use crate::parsers::parser::elements::eof;
fn keyword_follow_char(input: &str) -> IResult<&str, &str> |
pub fn sql_keyword(input: &str) -> IResult<&str, &str> {
alt((
terminated(tag_no_case("SELECT"), keyword_follow_char),
terminated(tag_no_case("FROM"), keyword_follow_char),
terminated(tag_no_case("WHERE"), keyword_follow_char),
terminated(tag_no_case("ORDER"), keyword_follow_char),... | {
peek(alt((
tag(" "),
tag("\n"),
tag(";"),
tag("("),
tag(")"),
tag("\t"),
tag(","),
tag("="),
eof,
)))(input)
} | identifier_body |
keywords.rs | use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case};
use nom::combinator::peek;
use nom::sequence::terminated;
use nom::IResult;
use crate::parsers::parser::elements::eof;
fn | (input: &str) -> IResult<&str, &str> {
peek(alt((
tag(" "),
tag("\n"),
tag(";"),
tag("("),
tag(")"),
tag("\t"),
tag(","),
tag("="),
eof,
)))(input)
}
pub fn sql_keyword(input: &str) -> IResult<&str, &str> {
alt((
terminated(tag... | keyword_follow_char | identifier_name |
keywords.rs | use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case};
use nom::combinator::peek;
use nom::sequence::terminated;
use nom::IResult;
use crate::parsers::parser::elements::eof;
fn keyword_follow_char(input: &str) -> IResult<&str, &str> {
peek(alt((
tag(" "),
tag("\n"),
tag(";"... | terminated(tag_no_case("ORDER"), keyword_follow_char),
terminated(tag_no_case("BY"), keyword_follow_char),
terminated(tag_no_case("ASC"), keyword_follow_char),
terminated(tag_no_case("DESC"), keyword_follow_char),
terminated(tag_no_case("LIMIT"), keyword_follow_char),
ter... | terminated(tag_no_case("SELECT"), keyword_follow_char),
terminated(tag_no_case("FROM"), keyword_follow_char),
terminated(tag_no_case("WHERE"), keyword_follow_char), | random_line_split |
dining_philosophers.rs | // http://rosettacode.org/wiki/Dining_philosophers
//! A Rust implementation of a solution for the Dining Philosophers Problem. We prevent a deadlock
//! by using Dijkstra's solution of making a single diner "left-handed." That is, all diners except
//! one pick up the chopstick "to their left" and then the chopstick ... | () {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
],
});
let philosophers = vec![
Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, ... | main | identifier_name |
dining_philosophers.rs | // http://rosettacode.org/wiki/Dining_philosophers
//! A Rust implementation of a solution for the Dining Philosophers Problem. We prevent a deadlock
//! by using Dijkstra's solution of making a single diner "left-handed." That is, all diners except
//! one pick up the chopstick "to their left" and then the chopstick ... |
}
struct Table {
forks: Vec<Mutex<()>>,
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
],
});
let philosophers = vec![
Philosopher::new("Baruch Spinoza... | {
let _left = table.forks[self.left].lock().unwrap();
let _right = table.forks[self.right].lock().unwrap();
println!("{} is eating.", self.name);
thread::sleep(Duration::from_secs(1));
println!("{} is done eating.", self.name);
} | identifier_body |
dining_philosophers.rs | // http://rosettacode.org/wiki/Dining_philosophers
//! A Rust implementation of a solution for the Dining Philosophers Problem. We prevent a deadlock
//! by using Dijkstra's solution of making a single diner "left-handed." That is, all diners except |
use std::thread;
use std::time::Duration;
use std::sync::{Mutex, Arc};
struct Philosopher {
name: String,
left: usize,
right: usize,
}
impl Philosopher {
fn new(name: &str, left: usize, right: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left: left,
... | //! one pick up the chopstick "to their left" and then the chopstick "to their right." The
//! remaining diner performs this in reverse. | random_line_split |
utmpx.rs | // This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <anonymousknight96@gmail.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
//! Aims to provide platform-independent methods to obtain login records
//!
//! **... | (&self) -> String {
chars2string!(self.inner.ut_host)
}
/// A.K.A. ut.ut_line
pub fn tty_device(&self) -> String {
chars2string!(self.inner.ut_line)
}
/// A.K.A. ut.ut_tv
pub fn login_time(&self) -> Tm {
time::at(Timespec::new(self.inner.ut_tv.tv_sec as i64,
... | host | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.