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 |
|---|---|---|---|---|
adv3.rs | #![allow(warnings)]
// Goal #1: Eliminate the borrow check error in the `remove` method.
pub struct Map<K: Eq, V> {
elements: Vec<(K, V)>,
}
impl<K: Eq, V> Map<K, V> { | pub fn new() -> Self {
Map { elements: vec![] }
}
pub fn insert(&mut self, key: K, value: V) {
self.elements.push((key, value));
}
pub fn get(&self, key: &K) -> Option<&V> {
self.elements.iter().rev().find(|pair| pair.0 == *key).map(|pair| &pair.1)
}
pub fn remove(... | random_line_split | |
fault.rs | use std::panic::catch_unwind;
use std::error::Error;
use std::fmt;
use std::io::{Write, stderr, Error as IoError, ErrorKind};
pub fn catch_fault() {
let result = catch_unwind(|| {
panic!("holy crap!");
});
println!("\n{:?}\n", result);
}
pub fn get_something() -> Result<(), String> {
Err("hol... | let _ = writeln!(stderr(), "error: {}", err);
while let Some(cause) = err.cause() {
let _ = writeln!(stderr(), "caused by: {}", cause);
err = cause;
}
}
pub fn demo_print_std_err() {
#[derive(Debug)]
struct SuperErrorSideKick;
impl fmt::Display for SuperErrorSideKick {
f... | pub fn print_error(mut err: &Error) { | random_line_split |
fault.rs | use std::panic::catch_unwind;
use std::error::Error;
use std::fmt;
use std::io::{Write, stderr, Error as IoError, ErrorKind};
pub fn catch_fault() {
let result = catch_unwind(|| {
panic!("holy crap!");
});
println!("\n{:?}\n", result);
}
pub fn get_something() -> Result<(), String> {
Err("hol... |
}
#[derive(Debug)]
struct SuperError;
impl fmt::Display for SuperError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "SuperError is here!")
}
}
impl Error for SuperError {
fn description(&self) -> &str {
"I'm the superhero of ... | {
"I'm SuperError side kick"
} | identifier_body |
fault.rs | use std::panic::catch_unwind;
use std::error::Error;
use std::fmt;
use std::io::{Write, stderr, Error as IoError, ErrorKind};
pub fn catch_fault() {
let result = catch_unwind(|| {
panic!("holy crap!");
});
println!("\n{:?}\n", result);
}
pub fn get_something() -> Result<(), String> {
Err("hol... | (&self) -> &str {
"I'm the superhero of errors"
}
fn cause(&self) -> Option<&Error> {
Some(&SuperErrorSideKick{})
}
}
let mut err = SuperError{};
println!("{:?}", err.cause());
print_error(&err);
}
pub fn err_propagation() -> Result<(), IoError> {
Er... | description | identifier_name |
extcolorbufferhalffloat.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 super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use canvas_traits::webgl::WebGLVersion;
use crat... |
impl EXTColorBufferHalfFloat {
fn new_inherited() -> EXTColorBufferHalfFloat {
Self {
reflector_: Reflector::new(),
}
}
}
impl WebGLExtension for EXTColorBufferHalfFloat {
type Extension = EXTColorBufferHalfFloat;
fn new(ctx: &WebGLRenderingContext) -> DomRoot<EXTColorBuffe... | } | random_line_split |
extcolorbufferhalffloat.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 super::{WebGLExtension, WebGLExtensionSpec, WebGLExtensions};
use canvas_traits::webgl::WebGLVersion;
use crat... | {
reflector_: Reflector,
}
impl EXTColorBufferHalfFloat {
fn new_inherited() -> EXTColorBufferHalfFloat {
Self {
reflector_: Reflector::new(),
}
}
}
impl WebGLExtension for EXTColorBufferHalfFloat {
type Extension = EXTColorBufferHalfFloat;
fn new(ctx: &WebGLRenderingC... | EXTColorBufferHalfFloat | identifier_name |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
... |
drop(CString::from_raw(s));
}
| {
return;
} | conditional_block |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
... | (s: String) -> *mut c_char {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
}
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn rs_cs... | rust_string_to_c | identifier_name |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
... | ///
/// This function will consume the provided data and use the underlying bytes to construct a new
/// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this
/// function; the provided data should *not* contain any 0 bytes in it.
///
/// Returns a valid pointer, or NULL
pub fn... |
/// Convert a String to C-compatible string | random_line_split |
common.rs | use std::ffi::CString;
use std::os::raw::c_char;
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
... |
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn rs_cstring_free(s: *mut c_char) {
if s.is_null() {
return;
}
drop(CString::from_raw(s));
}
| {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
} | identifier_body |
https.rs | extern crate rustls;
extern crate webpki_roots;
use std::net::SocketAddr;
use crate::name_server::RuntimeProvider;
use crate::tls::CLIENT_CONFIG;
use proto::xfer::{DnsExchange, DnsExchangeConnect};
use proto::TokioTime;
use trust_dns_https::{
HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClien... |
}
| {
https_test(ResolverConfig::cloudflare_https())
} | identifier_body |
https.rs | extern crate rustls;
extern crate webpki_roots;
use std::net::SocketAddr;
use crate::name_server::RuntimeProvider;
use crate::tls::CLIENT_CONFIG;
use proto::xfer::{DnsExchange, DnsExchangeConnect};
use proto::TokioTime;
use trust_dns_https::{
HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClien... | () {
https_test(ResolverConfig::cloudflare_https())
}
}
| test_cloudflare_https | identifier_name |
https.rs | extern crate rustls;
extern crate webpki_roots;
use std::net::SocketAddr;
use crate::name_server::RuntimeProvider;
use crate::tls::CLIENT_CONFIG;
use proto::xfer::{DnsExchange, DnsExchangeConnect};
use proto::TokioTime;
use trust_dns_https::{
HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClien... | let resolver =
TokioAsyncResolver::new(config, ResolverOpts::default(), io_loop.handle().clone())
.expect("failed to create resolver");
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
ass... | random_line_split | |
https.rs | extern crate rustls;
extern crate webpki_roots;
use std::net::SocketAddr;
use crate::name_server::RuntimeProvider;
use crate::tls::CLIENT_CONFIG;
use proto::xfer::{DnsExchange, DnsExchangeConnect};
use proto::TokioTime;
use trust_dns_https::{
HttpsClientConnect, HttpsClientResponse, HttpsClientStream, HttpsClien... |
}
// check if there is another connection created
let response = io_loop
.block_on(resolver.lookup_ip("www.example.com."))
.expect("failed to run lookup");
assert_eq!(response.iter().count(), 1);
for address in response.iter() {
if address.is_... | {
assert_eq!(
address,
IpAddr::V6(Ipv6Addr::new(
0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946,
))
);
} | conditional_block |
htmldatalistelement.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::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataLi... | }
}
let node: JSRef<Node> = NodeCast::from_ref(self);
let filter = box HTMLDataListOptionsFilter;
let window = window_from_node(node).root();
HTMLCollection::create(window.r(), node, filter)
}
} | #[jstraceable]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: JSRef<Element>, _root: JSRef<Node>) -> bool {
elem.is_htmloptionelement() | random_line_split |
htmldatalistelement.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::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataLi... | (&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLDataListElement)))
}
}
impl HTMLDataListElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLDataListElement {
... | is_htmldatalistelement | identifier_name |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/... |
#[cfg(test)]
mod test;
use result::*;
use rules::*;
use status::Status;
fn from_status_error_2_result_error(e: status::Error) -> Error {
Error {
pos: e.status.pos.clone(),
expected: e.expected,
line: e
.status
.text2parse
.lines()
.into_iter()
... | pub mod result;
#[macro_use]
pub mod rules;
pub(crate) mod status; | random_line_split |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/... | <'a, CustI>(text: &'a str, rules: &SetOfRules<CustI>) -> Result<'a> {
let status = Status::init(text);
expr::non_term::parse_ref_rule(rules, status, &RuleName("main".to_string()))
.map_err(from_status_error_2_result_error)?
.check_finalization()
}
// ----------------------------------------------... | parse | identifier_name |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/... |
// --------------------------------------------------------------------------------
// todo:
impl<'a> Status<'a> {
fn check_finalization(&self) -> Result<'a> {
if self.pos.n == self.text2parse.len() {
Ok(())
} else {
match &self.deeper_error {
None => Err(E... | {
let status = Status::init(text);
expr::non_term::parse_ref_rule(rules, status, &RuleName("main".to_string()))
.map_err(from_status_error_2_result_error)?
.check_finalization()
} | identifier_body |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/... | else {
match &self.deeper_error {
None => Err(Error {
pos: self.pos.clone(),
expected: im::vector!["not consumed full input...".to_owned()],
line: self
.text2parse
.lines()
... | {
Ok(())
} | conditional_block |
fragments.rs | tcx>, tcx: &ty::ctxt<'tcx>) -> String {
let repr = |mpi| move_data.path_loan_path(mpi).repr(tcx);
match *self {
Just(mpi) => repr(mpi),
AllButOneFrom(mpi) => format!("$(allbutone {})", repr(mpi)),
}
}
fn loan_path_user_string<'tcx>(&self,
... | {
let opt_variant_did = match parent.kind {
LpDowncast(_, variant_did) => Some(variant_did),
LpVar(..) | LpUpvar(..) | LpExtend(..) => enum_variant_did,
};
let loan_path_elem = LpInterior(InteriorField(new_field_name));
let new_lp_type = match new_field_name {
mc::NamedField(ast... | identifier_body | |
fragments.rs | Eq, PartialOrd, Ord)]
enum Fragment {
// This represents the path described by the move path index
Just(MovePathIndex),
// This represents the collection of all but one of the elements
// from an array at the path described by the move path index.
// Note that attached MovePathIndex should have me... | mc::NamedField(ast_name) =>
ty::named_element_ty(tcx, parent.to_type(), ast_name, opt_variant_did),
mc::PositionalField(idx) =>
ty::positional_element_ty(tcx, parent.to_type(), idx, opt_variant_did), | random_line_split | |
fragments.rs | .md`.
use self::Fragment::*;
use borrowck::InteriorKind::{InteriorField, InteriorElement};
use borrowck::LoanPath;
use borrowck::LoanPathKind::{LpVar, LpUpvar, LpDowncast, LpExtend};
use borrowck::LoanPathElem::{LpDeref, LpInterior};
use borrowck::move_data::InvalidMovePathIndex;
use borrowck::move_data::{MoveData, M... | <'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
lp: Rc<LoanPath<'tcx>>,
origin_id: Option<ast::NodeId>) {
match lp.kind {
LpVar(_) | LpUpvar... | add_fragment_siblings | identifier_name |
rtnl.rs | impl_var!(
/// Internet address families
Af, libc::c_uchar,
Inet => libc::AF_INET as libc::c_uchar,
Inet6 => libc::AF_INET6 as libc::c_uchar
);
impl_var!(
/// General address families for sockets
RtAddrFamily, u8,
Unspecified => libc::AF_UNSPEC as u8,
UnixOrLocal => libc::AF_UNIX as u8,... | Priority => libc::IFLA_PRIORITY,
Master => libc::IFLA_MASTER,
Wireless => libc::IFLA_WIRELESS,
Protinfo => libc::IFLA_PROTINFO,
Txqlen => libc::IFLA_TXQLEN,
Map => libc::IFLA_MAP,
Weight => libc::IFLA_WEIGHT,
Operstate => libc::IFLA_OPERSTATE,
Linkmode => libc::IFLA_LINKMODE,
Lin... | Link => libc::IFLA_LINK,
Qdisc => libc::IFLA_QDISC,
Stats => libc::IFLA_STATS,
Cost => libc::IFLA_COST, | random_line_split |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env:... |
// TODO: should InheritFd be hardcoded?
pub fn exec(&self) -> Result<(), ProcessError> {
let mut command = self.build_command();
command.stdout(InheritFd(1))
.stderr(InheritFd(2))
.stdin(InheritFd(0));
let exit = try!(command.status().map_err(|e| {
... | {
self.env.insert(key.to_string(), val.map(|t| t.to_c_str()));
self
} | identifier_body |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env:... | fn debug_string(&self) -> String {
let program = String::from_utf8_lossy(self.program.as_bytes_no_nul());
let mut program = program.into_string();
for arg in self.args.iter() {
program.push_char(' ');
let s = String::from_utf8_lossy(arg.as_bytes_no_nul());
... | random_line_split | |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env:... | (&self) -> Result<(), ProcessError> {
let mut command = self.build_command();
command.stdout(InheritFd(1))
.stderr(InheritFd(2))
.stdin(InheritFd(0));
let exit = try!(command.status().map_err(|e| {
process_error(format!("Could not execute process `{}`",
... | exec | identifier_name |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env:... |
}
pub fn build_command(&self) -> Command {
let mut command = Command::new(self.program.as_bytes_no_nul());
command.cwd(&self.cwd);
for arg in self.args.iter() {
command.arg(arg.as_bytes_no_nul());
}
for (k, v) in self.env.iter() {
let k = k.as_sl... | {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&output.status), Some(&output)))
} | conditional_block |
variance-trait-matching.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() {} | random_line_split | |
variance-trait-matching.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() {}
| {
let mut x = 1;
let y: &'static mut isize = Make::make(&mut x); //~ ERROR `x` does not live long enough
y
} | identifier_body |
variance-trait-matching.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 ... | () -> &'static mut isize {
let mut x = 1;
let y: &'static mut isize = Make::make(&mut x); //~ ERROR `x` does not live long enough
y
}
fn main() {}
| f | identifier_name |
mod.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 common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::build;
use graphql_syntax::parse_executable;
use graph... | {
let source_location = SourceLocationKey::standalone(fixture.file_name);
let ast = parse_executable(fixture.content, source_location).unwrap();
build(&TEST_SCHEMA, &ast.definitions)
.map(|definitions| print_ir(&TEST_SCHEMA, &definitions).join("\n\n"))
.map_err(|errors| {
errors
... | identifier_body | |
mod.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 common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::build;
use graphql_syntax::parse_executable;
use graph... | } | }) | random_line_split |
mod.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 common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::build;
use graphql_syntax::parse_executable;
use graph... | (fixture: &Fixture<'_>) -> Result<String, String> {
let source_location = SourceLocationKey::standalone(fixture.file_name);
let ast = parse_executable(fixture.content, source_location).unwrap();
build(&TEST_SCHEMA, &ast.definitions)
.map(|definitions| print_ir(&TEST_SCHEMA, &definitions).join("\n\n")... | transform_fixture | identifier_name |
bunch.rs |
#![feature(test)]
extern crate misc;
extern crate lsm;
extern crate test;
fn tid() -> String {
// TODO use the rand crate
fn bytes() -> std::io::Result<[u8;16]> {
use std::fs::OpenOptions;
let mut f = try!(OpenOptions::new()
.read(true)
.open("/dev/urandom"));
... | (b: &mut test::Bencher) {
fn f() -> lsm::Result<bool> {
//println!("running");
let db = try!(lsm::db::new(tempfile("bunch"), lsm::DEFAULT_SETTINGS));
const NUM : usize = 10000;
let mut a = Vec::new();
for i in 0.. 10 {
let g = try!(db.WriteSegmentFromSortedSeque... | bunch | identifier_name |
bunch.rs | #![feature(test)]
extern crate misc;
extern crate lsm;
extern crate test;
fn tid() -> String {
// TODO use the rand crate
fn bytes() -> std::io::Result<[u8;16]> {
use std::fs::OpenOptions;
let mut f = try!(OpenOptions::new()
.read(true)
.open("/dev/urandom"));
... | {
let lck = try!(db.GetWriteLock());
try!(lck.commitSegments(a.clone()));
}
let g3 = try!(db.merge(0, 2, None));
assert!(g3.is_some());
let g3 = g3.unwrap();
{
let lck = try!(db.GetWriteLock());
try!(lck.commitMerge(g3));
... | } | random_line_split |
bunch.rs |
#![feature(test)]
extern crate misc;
extern crate lsm;
extern crate test;
fn tid() -> String {
// TODO use the rand crate
fn bytes() -> std::io::Result<[u8;16]> {
use std::fs::OpenOptions;
let mut f = try!(OpenOptions::new()
.read(true)
.open("/dev/urandom"));
... |
let ba = bytes().unwrap();
to_hex_string(&ba)
}
fn tempfile(base: &str) -> String {
std::fs::create_dir("tmp");
let file = "tmp/".to_string() + base + "_" + &tid();
file
}
#[bench]
fn bunch(b: &mut test::Bencher) {
fn f() -> lsm::Result<bool> {
//println!("running");
let db =... | {
let strs: Vec<String> = ba.iter()
.map(|b| format!("{:02X}", b))
.collect();
strs.connect("")
} | identifier_body |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::OR {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... | #[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - Timer input 1 remap"]
#[inline(alw... | impl W {
#[doc = r" Reset value of the register"] | random_line_split |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::OR {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... | {
bits: u8,
}
impl RMPR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _RMPW<'a> {
w: &'a mut W,
}
impl<'a> _RMPW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub uns... | RMPR | identifier_name |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::OR {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... |
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct RMPR {
bits: u8,
}
impl RMPR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
... | {
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![deny(unsafe_code)]
extern crate gfx;
extern crate ipc_channel;
extern crate metrics;
extern crate msg;
extern ... | // This module contains traits in layout used generically
// in the rest of Servo.
// The traits are here instead of in layout so
// that these modules won't have to depend on layout.
use gfx::font_cache_thread::FontCacheThread;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use metrics::PaintTimeMetrics;
use msg... | random_line_split | |
css_section.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use CssSectionType;
use ffi;
use glib::translate::*;
glib_wrapper! {
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_sectio... | (&self) -> CssSectionType {
unsafe {
from_glib(ffi::gtk_css_section_get_section_type(self.to_glib_none().0))
}
}
pub fn get_start_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_line(self.to_glib_none().0)
}
}
pub fn get_start_positi... | get_section_type | identifier_name |
css_section.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use CssSectionType;
use ffi;
use glib::translate::*;
glib_wrapper! {
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_sectio... | }
} |
pub fn get_start_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
} | random_line_split |
css_section.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use CssSectionType;
use ffi;
use glib::translate::*;
glib_wrapper! {
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_sectio... |
pub fn get_end_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_position(self.to_glib_none().0)
}
}
//pub fn get_file(&self) -> /*Ignored*/Option<gio::File> {
// unsafe { TODO: call ffi::gtk_css_section_get_file() }
//}
pub fn get_parent(&self) ->... | {
unsafe {
ffi::gtk_css_section_get_end_line(self.to_glib_none().0)
}
} | identifier_body |
validators.rs | // src/common/validation/validators.rs
/// Validators
// Import Modules
// External
use ::regex::Regex;
/// Check that a field is not supplied, or None
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn empty<T>(val: &Option<T>) -> b... |
/// Check that two values are identical
///
/// # Arguments
/// `val1` - Generic type T
/// `val2` - Generic type T
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn equals<T: PartialEq>(val1: T, val2: T) -> bool{
val1 == val2
}
/// Check if a string matches a regular expression
///
///... | {
match val{
Some(v) => !v.is_empty(),
None => false
}
} | identifier_body |
validators.rs | // src/common/validation/validators.rs
/// Validators
// Import Modules
// External
use ::regex::Regex;
/// Check that a field is not supplied, or None
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn empty<T>(val: &Option<T>) -> b... | (value: &str, regex: &str) -> bool{
let re = Regex::new(regex).unwrap();
re.is_match(value)
}
| matches | identifier_name |
validators.rs | // src/common/validation/validators.rs
/// Validators
// Import Modules
// External
use ::regex::Regex;
/// Check that a field is not supplied, or None
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn empty<T>(val: &Option<T>) -> b... | /// Check that a field is not empty
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn not_empty<T>(val: Option<T>) -> bool{
match val{
Some(_) => true,
None => false
}
}
/// Check that a String field is not emp... | }
}
| random_line_split |
voxel_tree.rs | #![cfg_attr(test, feature(test))]
use cgmath::Ray3;
use std::mem;
use std::ops::{Deref, DerefMut};
use raycast;
use voxel;
use voxel::Voxel;
#[derive(Debug)]
pub struct VoxelTree {
/// The log_2 of the tree's size.
lg_size: u8,
/// Force the top level to always be branches;
/// it saves a branch in the grow ... | () {
let mut tree: VoxelTree<i32> = VoxelTree::new();
*tree.get_mut_or_create(voxel::Bounds::new(1, 1, 1, 0)) = TreeBody::Leaf(1);
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 1));
tree.grow_to_hold(voxel::Bounds::new(0, 0, 0, 2));
tree.grow_to_hold(voxel::Bounds::new(-32, 32, -128, 3));
asser... | grow_is_transparent | identifier_name |
voxel_tree.rs | #![cfg_attr(test, feature(test))]
use cgmath::Ray3;
use std::mem;
use std::ops::{Deref, DerefMut};
use raycast;
use voxel;
use voxel::Voxel;
#[derive(Debug)]
pub struct VoxelTree {
/// The log_2 of the tree's size.
lg_size: u8,
/// Force the top level to always be branches;
/// it saves a branch in the grow ... | ,
];
// NB: The children are half the size of the tree itself,
// but tree.lg_size=0 means it extends tree.lg_size=0 in *each direction*,
// so the "actual" size of the tree as a voxel would be tree.lg_size+1.
let child_lg_size = self.lg_size as i16;
let mut make_bounds = |coords: [usize; 3]| {
... | {0} | conditional_block |
voxel_tree.rs | #![cfg_attr(test, feature(test))]
use cgmath::Ray3;
use std::mem;
use std::ops::{Deref, DerefMut};
use raycast;
use voxel;
use voxel::Voxel;
#[derive(Debug)]
pub struct VoxelTree {
/// The log_2 of the tree's size.
lg_size: u8,
/// Force the top level to always be branches;
/// it saves a branch in the grow ... |
pub fn cast_ray<'a, Act, R>(
&'a self,
ray: &Ray3<f32>,
act: &mut Act,
) -> Option<R>
where
// TODO: Does this *have* to be callback-based?
Act: FnMut(voxel::Bounds, &'a Voxel) -> Option<R>
{
let coords = [
if ray.origin.x >= 0.0 {1} else {0},
if ray.origin.y >= 0.0 {... | {
if !self.contains_bounds(voxel) {
return None
}
let get_step = |branch| {
match branch {
&mut TreeBody::Branch(ref mut branches) => Ok(branches.deref_mut()),
_ => Err(()),
}
};
match self.find_mut(voxel, get_step) {
Ok(&mut TreeBody::Leaf(ref mut t)) => So... | identifier_body |
voxel_tree.rs | #![cfg_attr(test, feature(test))]
use cgmath::Ray3;
use std::mem;
use std::ops::{Deref, DerefMut};
use raycast;
use voxel;
use voxel::Voxel;
#[derive(Debug)]
pub struct VoxelTree {
/// The log_2 of the tree's size.
lg_size: u8,
/// Force the top level to always be branches;
/// it saves a branch in the grow ... | lhh: TreeBody,
hll: TreeBody,
hlh: TreeBody,
hhl: TreeBody,
hhh: TreeBody,
}
/// The main, recursive, tree-y part of the `VoxelTree`.
#[derive(Debug, PartialEq, Eq)]
pub enum TreeBody {
Empty,
Leaf(Voxel),
Branch(Box<Branches>),
}
impl Branches {
pub fn empty() -> Branches {
Branches {
lll... | lhl: TreeBody, | random_line_split |
read.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 std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debu... | self.index += 1;
Ok(ch)
}
fn peek(&mut self) -> anyhow::Result<u8> {
if self.index >= self.slice.len() {
bail!("eof while peeking next byte");
}
Ok(self.slice[self.index])
}
#[inline]
fn read_count(&self) -> usize {
self.index
}
... | let ch = self.slice[self.index]; | random_line_split |
read.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 std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debu... |
let borrowed = &self.slice[self.index..(self.index + len)];
self.index += len;
Ok(Reference::Borrowed(borrowed))
}
}
impl<'de, R> DeRead<'de> for IoRead<R>
where
R: io::Read,
{
fn next(&mut self) -> anyhow::Result<u8> {
match self.peeked.take() {
Some(peeked) =>... | {
bail!("eof while parsing bytes/string");
} | conditional_block |
read.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 std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debu... | <'a>(&'a [u8]);
#[cfg(feature = "debug_bytes")]
impl<'a> fmt::LowerHex for ByteBuf<'a> {
fn fmt(&self, fmtr: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
for byte in self.0 {
let val = byte.clone();
if (val >= b'-' && val <= b'9')
|| (val >= b'A' && val <=... | ByteBuf | identifier_name |
read.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 std::io;
use std::result;
use anyhow::{bail, Context as _};
use byteorder::{ByteOrder, NativeEndian};
#[cfg(feature = "debu... |
}
pub trait DeRead<'de> {
/// read next byte (if peeked byte not discarded return it)
fn next(&mut self) -> anyhow::Result<u8>;
/// peek next byte (peeked byte should come in next and next_bytes unless discarded)
fn peek(&mut self) -> anyhow::Result<u8>;
/// how many bytes have been read so far.
... | {
for byte in self.0 {
let val = byte.clone();
if (val >= b'-' && val <= b'9')
|| (val >= b'A' && val <= b'Z')
|| (val >= b'a' && val <= b'z')
|| val == b'_'
{
fmtr.write_fmt(format_args!("{}", val as char))?;
... | identifier_body |
htmlbuttonelement.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::activation::Activatable;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLButtonElementBind... |
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
fn canceled_activation(&self) {
}
// https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
let ty = self.button_type.get();
... | {
} | identifier_body |
htmlbuttonelement.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::activation::Activatable;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLButtonElementBind... | (&self) {
}
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
fn canceled_activation(&self) {
}
// https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
let ty = self.button_... | pre_click_activation | identifier_name |
htmlbuttonelement.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::activation::Activatable;
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLButtonElementBind... | }
// https://html.spec.whatwg.org/multipage/#implicit-submission
#[allow(unsafe_code)]
fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) {
let doc = document_from_node(*self);
let node = NodeCast::from_ref(doc.r());
let owner = self.form_o... | random_line_split | |
cli.rs | //! Command argument types
//! The deserialized structures of the command args.
#![allow(non_camel_case_types,non_snake_case)]
use core::fmt;
use core::str::FromStr;
use docopt;
use opengl_graphics::OpenGL;
use rustc_serialize::{Decodable,Decoder};
use std::net;
docopt!(pub Args derive Debug,concat!("
Usage: ",PROGR... | (pub net::IpAddr);
impl Decodable for Host{
fn decode<D: Decoder>(d: &mut D) -> Result<Self,D::Error>{
let str = try!(d.read_str());
let str = &*str;
Ok(Host(match net::IpAddr::from_str(str){
Ok(addr) => addr,
Err(_) => try!(try!(try!(
net::lookup_host(str).map_err(|_| d.error("Error when lookup_hos... | Host | identifier_name |
cli.rs | //! Command argument types
//! The deserialized structures of the command args.
#![allow(non_camel_case_types,non_snake_case)]
use core::fmt;
use core::str::FromStr;
use docopt;
use opengl_graphics::OpenGL;
use rustc_serialize::{Decodable,Decoder};
use std::net;
docopt!(pub Args derive Debug,concat!("
Usage: ",PROGR... | impl fmt::Debug for GlVersion{
fn fmt(&self,f: &mut fmt::Formatter) -> fmt::Result{
write!(f,"{}",match self.0{
OpenGL::V2_0 => "v2.0",
OpenGL::V2_1 => "v2.1",
OpenGL::V3_0 => "v3.0",
OpenGL::V3_1 => "v3.1",
OpenGL::V3_2 => "v3.2",
OpenGL::V3_3 => "v3.3",
OpenGL::V4_0 => "v4.0",
OpenGL::V4_1 ... | random_line_split | |
test_cargo_publish.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::io::{Cursor, SeekFrom};
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
use url::Url;
use support::{project, execs};
use support::{UPDATING, PACKAGING, UPLOADING};
use support::paths;
use support::git::repo;
use hamcrest::assert_that... |
fn upload() -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
fn setup() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config).unwrap().write_all(&format!(r#"
[registry]
index = "{reg}"
t... | { paths::root().join("upload") } | identifier_body |
test_cargo_publish.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::io::{Cursor, SeekFrom};
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
use url::Url; | use support::git::repo;
use hamcrest::assert_that;
fn registry_path() -> PathBuf { paths::root().join("registry") }
fn registry() -> Url { Url::from_file_path(&*registry_path()).ok().unwrap() }
fn upload_path() -> PathBuf { paths::root().join("upload") }
fn upload() -> Url { Url::from_file_path(&*upload_path()).ok().... |
use support::{project, execs};
use support::{UPDATING, PACKAGING, UPLOADING};
use support::paths; | random_line_split |
test_cargo_publish.rs | use std::io::prelude::*;
use std::fs::{self, File};
use std::io::{Cursor, SeekFrom};
use std::path::PathBuf;
use flate2::read::GzDecoder;
use tar::Archive;
use url::Url;
use support::{project, execs};
use support::{UPDATING, PACKAGING, UPLOADING};
use support::paths;
use support::git::repo;
use hamcrest::assert_that... | () -> Url { Url::from_file_path(&*upload_path()).ok().unwrap() }
fn setup() {
let config = paths::root().join(".cargo/config");
fs::create_dir_all(config.parent().unwrap()).unwrap();
File::create(&config).unwrap().write_all(&format!(r#"
[registry]
index = "{reg}"
token = "ap... | upload | identifier_name |
suback.rs | use std::io::{self, Read, Write};
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder::{self, WriteBytesExt, ReadBytesExt};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[repr... | (&self) -> &[SubscribeReturnCode] {
&self.subscribes[..]
}
}
impl<'a> Encodable<'a> for SubackPacketPayload {
type Err = SubackPacketPayloadError;
fn encode<W: Write>(&self, writer: &mut W) -> Result<(), Self::Err> {
for code in self.subscribes.iter() {
try!(writer.write_u8(*co... | subscribes | identifier_name |
suback.rs | use std::io::{self, Read, Write};
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder::{self, WriteBytesExt, ReadBytesExt};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[repr... |
fn encoded_variable_headers_length(&self) -> u32 {
self.packet_identifier.encoded_length()
}
fn decode_packet<R: Read>(reader: &mut R, fixed_header: FixedHeader) -> Result<Self, PacketError<'a, Self>> {
let packet_identifier: PacketIdentifier = try!(PacketIdentifier::decode(reader));
... | {
try!(self.packet_identifier.encode(writer));
Ok(())
} | identifier_body |
suback.rs | use std::io::{self, Read, Write};
use std::error::Error;
use std::fmt;
use std::convert::From;
use byteorder::{self, WriteBytesExt, ReadBytesExt};
use control::{FixedHeader, PacketType, ControlType};
use control::variable_header::PacketIdentifier;
use packet::{Packet, PacketError};
use {Encodable, Decodable};
#[repr... | match self {
&SubackPacketPayloadError::IoError(ref err) => err.description(),
&SubackPacketPayloadError::InvalidSubscribeReturnCode(..) => "Invalid subscribe return code",
}
}
fn cause(&self) -> Option<&Error> {
match self {
&SubackPacketPayloadError... | fn description(&self) -> &str { | random_line_split |
sqlite.rs | /*
* database/handle.rs
*
* markov-music - A music player that uses Markov chains to choose songs
* Copyright (c) 2017-2018 Ammon Smith
*
* markov-music 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, ... | {
conn: SqliteConnection,
}
impl SqliteDatabase {
pub fn new<S: AsRef<str>>(url: S) -> Result<Self> {
let conn = SqliteConnection::establish(url.as_ref())?;
Ok(SqliteDatabase { conn: conn })
}
}
impl Database for SqliteDatabase {
type Error = Error;
fn modify_weight(
&mut... | SqliteDatabase | identifier_name |
sqlite.rs | /*
* database/handle.rs
*
* markov-music - A music player that uses Markov chains to choose songs
* Copyright (c) 2017-2018 Ammon Smith
*
* markov-music 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, ... | Ok(())
})
}
fn clear(&mut self, song: &str) -> Result<()> {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
diesel::delete(associations::table.filter(dsl::song.eq(song)))
.execute(&self.conn)?;
Ok(())
... | diesel::replace_into(starters::table)
.values(&[new_assoc])
.execute(&self.conn)?;
| random_line_split |
sqlite.rs | /*
* database/handle.rs
*
* markov-music - A music player that uses Markov chains to choose songs
* Copyright (c) 2017-2018 Ammon Smith
*
* markov-music 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, ... | Ok(())
})
}
fn clear(&mut self, song: &str) -> Result<()> {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
diesel::delete(associations::table.filter(dsl::song.eq(song)))
.execute(&self.conn)?;
Ok(())
... | {
self.conn.transaction::<(), Error, _>(|| {
use self::associations::dsl;
let row = associations::table
.find((song, next))
.first::<Association>(&self.conn)
.optional()?;
let weight = row.map(|assoc| assoc.weight).unwrap_or(0... | identifier_body |
local-inlining-but-not-all.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=lazy
// compile-flags:-Zinline-in-all-cgus=no
#![allow(dead_code)]
#![crate_type="lib"]
mod inline {
//~ MONO_ITEM fn inline::inlined_function @@ local_inli... |
}
pub mod user1 {
use super::inline;
//~ MONO_ITEM fn user1::foo @@ local_inlining_but_not_all-user1[External]
pub fn foo() {
inline::inlined_function();
}
}
pub mod user2 {
use super::inline;
//~ MONO_ITEM fn user2::bar @@ local_inlining_but_not_all-user2[External]
pub fn bar()... | {
} | identifier_body |
local-inlining-but-not-all.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation | #![allow(dead_code)]
#![crate_type="lib"]
mod inline {
//~ MONO_ITEM fn inline::inlined_function @@ local_inlining_but_not_all-inline[External]
#[inline]
pub fn inlined_function()
{
}
}
pub mod user1 {
use super::inline;
//~ MONO_ITEM fn user1::foo @@ local_inlining_but_not_all-user1[Ex... | // incremental
// compile-flags:-Zprint-mono-items=lazy
// compile-flags:-Zinline-in-all-cgus=no
| random_line_split |
local-inlining-but-not-all.rs | //
// We specify incremental here because we want to test the partitioning for
// incremental compilation
// incremental
// compile-flags:-Zprint-mono-items=lazy
// compile-flags:-Zinline-in-all-cgus=no
#![allow(dead_code)]
#![crate_type="lib"]
mod inline {
//~ MONO_ITEM fn inline::inlined_function @@ local_inli... | ()
{
}
}
pub mod user1 {
use super::inline;
//~ MONO_ITEM fn user1::foo @@ local_inlining_but_not_all-user1[External]
pub fn foo() {
inline::inlined_function();
}
}
pub mod user2 {
use super::inline;
//~ MONO_ITEM fn user2::bar @@ local_inlining_but_not_all-user2[External]
... | inlined_function | identifier_name |
mod.rs | mut [u64] = unsafe { cast::transmute(slice) };
for dest in as_u64.mut_iter() {
*dest = self.next_u64();
}
// the above will have filled up the vector as much as
// possible in multiples of 8 bytes.
let mut remaining = dest.len() % 8;
// space for a u32
... | (&mut self, n: uint) -> bool {
n == 0 || self.gen_integer_range(0, n) == 0
}
/// Return a random string of the specified length composed of
/// A-Z,a-z,0-9.
///
/// # Example
///
/// ```rust
/// use std::rand;
/// use std::rand::Rng;
///
/// fn main() {
/// pr... | gen_weighted_bool | identifier_name |
mod.rs |
/// `high`). Fails if `low >= high`.
///
/// This gives a uniform distribution (assuming this RNG is itself
/// uniform), even for edge cases like `gen_integer_range(0u8,
/// 170)`, which a naive modulo operation would return numbers
/// less than 85 with double the probability to those greater... | random_line_split | ||
mod.rs | mut [u64] = unsafe { cast::transmute(slice) };
for dest in as_u64.mut_iter() {
*dest = self.next_u64();
}
// the above will have filled up the vector as much as
// possible in multiples of 8 bytes.
let mut remaining = dest.len() % 8;
// space for a u32
... |
/// An [Xorshift random number
/// generator](http://en.wikipedia.org/wiki/Xorshift).
///
/// The Xorshift algorithm is not suitable for cryptographic purposes
/// but is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng`.
pub struct XorShiftRng {
p... | {
XorShiftRng::new()
} | identifier_body |
example.rs | pub fn verse(n: i32) -> String {
match n {
0 => "No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\
Take it down and ... | pub fn sing(start: i32, end: i32) -> String {
let mut song = Vec::new();
for n in (end.. start + 1).rev() {
song.push(verse(n))
}
song.connect("\n")
} | }
}
| random_line_split |
example.rs | pub fn verse(n: i32) -> String |
pub fn sing(start: i32, end: i32) -> String {
let mut song = Vec::new();
for n in (end.. start + 1).rev() {
song.push(verse(n))
}
song.connect("\n")
}
| {
match n {
0 => "No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\
Take it down and pass it around, no more bottles... | identifier_body |
example.rs | pub fn | (n: i32) -> String {
match n {
0 => "No more bottles of beer on the wall, no more bottles of beer.\n\
Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(),
1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\
Take it down and pass it arou... | verse | identifier_name |
unboxed-closures-blanket-fn-mut.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 |
unboxed-closures-blanket-fn-mut.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 b(f: &mut FnMut() -> i32) -> i32 {
a(f)
}
fn c<F:FnMut() -> i32>(f: &mut F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&mut || 22);
assert_eq!(x, 22);
let x = c(&mut || 22);
assert_eq!(x, 22);
}
| {
f()
} | identifier_body |
unboxed-closures-blanket-fn-mut.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 ... | (f: &mut FnMut() -> i32) -> i32 {
a(f)
}
fn c<F:FnMut() -> i32>(f: &mut F) -> i32 {
a(f)
}
fn main() {
let z: isize = 7;
let x = b(&mut || 22);
assert_eq!(x, 22);
let x = c(&mut || 22);
assert_eq!(x, 22);
}
| b | identifier_name |
simd.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... |
#[inline(never)]
fn zzz() { () } |
zzz();
} | random_line_split |
simd.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... | () { () }
| zzz | identifier_name |
simd.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... |
#[inline(never)]
fn zzz() { () }
| {
let i8x16 = i8x16(0i8, 1i8, 2i8, 3i8, 4i8, 5i8, 6i8, 7i8,
8i8, 9i8, 10i8, 11i8, 12i8, 13i8, 14i8, 15i8);
let i16x8 = i16x8(16i16, 17i16, 18i16, 19i16, 20i16, 21i16, 22i16, 23i16);
let i32x4 = i32x4(24i32, 25i32, 26i32, 27i32);
let i64x2 = i64x2(28i64, 29i64);
let u8x16 = u... | identifier_body |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | use std::str;
pub struct Wal {
fs: File,
dir: String,
}
impl Wal {
pub fn new(dir: &str) -> Result<Wal, io::Error> {
let mut tmp = OsString::new();
let mut big_path = PathBuf::new();
let mut fss = read_dir(&dir);
if fss.is_err() {
DirBuilder::new().recursive(tr... | use std::path::{PathBuf, Path}; | random_line_split |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... |
Ok(())
}
pub fn save(&mut self, mtype: u8, msg: &Vec<u8>) -> io::Result<usize> {
let mlen = msg.len() as u32;
if mlen == 0 {
return Ok(0);
}
let len_bytes: [u8; 4] = unsafe { transmute(mlen.to_le()) };
let type_bytes: [u8; 1] = unsafe { transmute(mty... | {
let mut delname = (height - 2).to_string();
delname = delname + ".log";
let delfilename = pathname + &*delname;
let _ = ::std::fs::remove_file(delfilename);
} | conditional_block |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | }
}
if fnum == 0 {
tmp = OsString::from("1");
let fpath = dir.to_string() + "/1.log";
big_path = Path::new(&*fpath).to_path_buf();
}
let fs = OpenOptions::new().read(true).create(true).write(true).open(big_path)?;
let hstr = tmp.i... | {
let mut tmp = OsString::new();
let mut big_path = PathBuf::new();
let mut fss = read_dir(&dir);
if fss.is_err() {
DirBuilder::new().recursive(true).create(dir).unwrap();
fss = read_dir(&dir);
}
let mut fnum = 0;
for dir_entry in fss? {
... | identifier_body |
wal.rs | // CITA
// Copyright 2016-2017 Cryptape Technologies LLC.
// This program is free software: you can redistribute it
// and/or modify it under the terms of the GNU General Public
// License as published by the Free Software Foundation,
// either version 3 of the License, or (at your option) any
// later version.
// Th... | (&mut self, mtype: u8, msg: &Vec<u8>) -> io::Result<usize> {
let mlen = msg.len() as u32;
if mlen == 0 {
return Ok(0);
}
let len_bytes: [u8; 4] = unsafe { transmute(mlen.to_le()) };
let type_bytes: [u8; 1] = unsafe { transmute(mtype.to_le()) };
self.fs.seek(io... | save | identifier_name |
forcetouchevent.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::ForceTouchEventBinding;
use dom::bindings::codegen::Bindings::ForceTouchEven... | type_: DOMString,
force: f32) -> Root<ForceTouchEvent> {
let event = box ForceTouchEvent::new_inherited(force);
let ev = reflect_dom_object(event, GlobalRef::Window(window), ForceTouchEventBinding::Wrap);
ev.upcast::<UIEvent>().InitUIEvent(type_, true, true, Some(wi... | pub fn new(window: &Window, | random_line_split |
forcetouchevent.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::ForceTouchEventBinding;
use dom::bindings::codegen::Bindings::ForceTouchEven... | (force: f32) -> ForceTouchEvent {
ForceTouchEvent {
uievent: UIEvent::new_inherited(),
force: force,
}
}
pub fn new(window: &Window,
type_: DOMString,
force: f32) -> Root<ForceTouchEvent> {
let event = box ForceTouchEvent::new_inheri... | new_inherited | identifier_name |
forcetouchevent.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::ForceTouchEventBinding;
use dom::bindings::codegen::Bindings::ForceTouchEven... |
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.uievent.IsTrusted()
}
}
| {
Finite::wrap(2.0)
} | identifier_body |
webvr_traits.rs | /* This Source Code Form is subject to the terms of the Mozilla Public | use webvr::*;
pub type WebVRResult<T> = Result<T, String>;
// Messages from Script thread to WebVR thread.
#[derive(Deserialize, Serialize)]
pub enum WebVRMsg {
RegisterContext(PipelineId),
UnregisterContext(PipelineId),
PollEvents(IpcSender<bool>),
GetDisplays(IpcSender<WebVRResult<Vec<VRDisplayData>... | * 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 ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId; | random_line_split |
webvr_traits.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 ipc_channel::ipc::IpcSender;
use msg::constellation_msg::PipelineId;
use webvr::*;
pub type WebVRResult<T> = ... | {
RegisterContext(PipelineId),
UnregisterContext(PipelineId),
PollEvents(IpcSender<bool>),
GetDisplays(IpcSender<WebVRResult<Vec<VRDisplayData>>>),
GetFrameData(PipelineId, u64, f64, f64, IpcSender<WebVRResult<VRFrameData>>),
ResetPose(PipelineId, u64, IpcSender<WebVRResult<VRDisplayData>>),
... | WebVRMsg | identifier_name |
run.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.... | (
panic_handler: Arc<PanicHandler>,
_http_server: Option<HttpServer>,
_ipc_server: Option<IpcServer>,
_dapps_server: Option<WebappServer>,
_signer_server: Option<SignerServer>
) {
let exit = Arc::new(Condvar::new());
// Handle possible exits
let e = exit.clone();
CtrlC::set_handler(move || { e.notify_all(); ... | wait_for_exit | identifier_name |
run.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.... | let miner = Miner::new(cmd.miner_options, cmd.gas_pricer.into(), &spec, Some(account_provider.clone()));
miner.set_author(cmd.miner_extras.author);
miner.set_gas_floor_target(cmd.miner_extras.gas_floor_target);
miner.set_gas_ceil_target(cmd.miner_extras.gas_ceil_target);
miner.set_extra_data(cmd.miner_extras.extra... |
// create miner | random_line_split |
run.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.... | else {
sync_config.subprotocol_name.clone_from_slice(spec.subprotocol_name().as_bytes());
}
sync_config.fork_block = spec.fork_block();
sync_config.warp_sync = cmd.warp_sync;
// prepare account provider
let account_provider = Arc::new(try!(prepare_account_provider(&cmd.dirs, cmd.acc_conf)));
// create miner
... | {
warn!("Your chain specification's subprotocol length is not 3. Ignoring.");
} | conditional_block |
run.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 prepare_account_provider(dirs: &Directories, cfg: AccountsConfig) -> Result<AccountProvider, String> {
use ethcore::ethstore::EthStore;
use ethcore::ethstore::dir::DiskDirectory;
let passwords = try!(passwords_from_files(cfg.password_files));
let dir = Box::new(try!(DiskDirectory::create(dirs.keys.clone()).m... | {
Err("daemon is no supported on windows".into())
} | identifier_body |
util.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | {
location: PointRef,
name: String,
}
impl From<FeatureRef> for Feature {
fn from(r: FeatureRef) -> Feature {
let mut f = Feature::default();
f.set_name(r.name);
f.mut_location().set_latitude(r.location.latitude);
f.mut_location().set_longitude(r.location.longitude);
... | FeatureRef | identifier_name |
util.rs | // Copyright 2017 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | f.mut_location().set_longitude(r.location.longitude);
f
}
}
pub fn load_db() -> Vec<Feature> {
let data = include_str!("db.json");
let features: Vec<FeatureRef> = serde_json::from_str(data).unwrap();
features.into_iter().map(From::from).collect()
}
pub fn same_point(lhs: &Point, rhs: &... | random_line_split | |
init.rs | use std::sync::{atomic, mpsc};
use std::{io, process, thread};
use ctrlc;
use crate::control::acio;
use crate::{args, control, disk, log, rpc, throttle, tracker};
use crate::{CONFIG, SHUTDOWN, THROT_TOKS};
pub fn init(args: args::Args) -> Result<(), ()> {
if let Some(level) = args.level {
log::log_init(l... | {
ctrlc::set_handler(move || {
if SHUTDOWN.load(atomic::Ordering::SeqCst) {
info!("Terminating process!");
process::abort();
} else {
info!("Shutting down cleanly. Interrupt again to shut down immediately.");
SHUTDOWN.store(true, atomic::Ordering::SeqC... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.