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 |
|---|---|---|---|---|
send_msg.rs | //! Client Node Example.
//!
//! The node sends a message (atom) to the specified erlang node.
//!
//! # Usage Examples
//!
//! ```bash
//! $ cargo run --example send_msg -- --help
//! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello
//! ```
extern crate clap;
extern crate ... | () {
let matches = App::new("send_msg")
.arg(
Arg::with_name("EPMD_HOST")
.short("h")
.takes_value(true)
.default_value("127.0.0.1"),
)
.arg(
Arg::with_name("EPMD_PORT")
.short("p")
.takes_value(... | main | identifier_name |
trait-coercion-generic.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let a = Struct { x: 1, y: 2 };
let b: Box<Trait<&'static str>> = box a;
b.f("Mary");
let c: &Trait<&'static str> = &a;
c.f("Joe");
} |
pub fn main() { | random_line_split |
trait-coercion-generic.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let a = Struct { x: 1, y: 2 };
let b: Box<Trait<&'static str>> = box a;
b.f("Mary");
let c: &Trait<&'static str> = &a;
c.f("Joe");
}
| main | identifier_name |
trait-coercion-generic.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
pub fn main() {
let a = Struct { x: 1, y: 2 };
let b: Box<Trait<&'static str>> = box a;
b.f("Mary");
let c: &Trait<&'static str> = &a;
c.f("Joe");
}
| {
println!("Hi, {}!", x);
} | identifier_body |
basic_block.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub fn as_value(self) -> Value {
unsafe {
Value(llvm::LLVMBasicBlockAsValue(self.get()))
}
}
pub fn pred_iter(self) -> Preds<'static> {
self.as_value().user_iter()
.filter(|user| user.is_a_terminator_inst())
.map(|user| user.get_parent().unwrap())... | {
let BasicBlock(v) = *self; v
} | identifier_body |
basic_block.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (pub BasicBlockRef);
pub type Preds<'a> = Map<'a, Value, BasicBlock, Filter<'a, Value, Users>>;
/**
* Wrapper for LLVM BasicBlockRef
*/
impl BasicBlock {
pub fn get(&self) -> BasicBlockRef {
let BasicBlock(v) = *self; v
}
pub fn as_value(self) -> Value {
unsafe {
Value(llvm:... | BasicBlock | identifier_name |
basic_block.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
}
} | let mut iter = self.pred_iter();
match (iter.next(), iter.next()) {
(Some(first), None) => Some(first),
_ => None | random_line_split |
array.rs | //! Generic-length array strategy.
// Adapted from proptest's array code
// Copyright 2017 Jason Lingle
use core::{marker::PhantomData, mem::MaybeUninit};
use proptest::{
strategy::{NewTree, Strategy, ValueTree},
test_runner::TestRunner,
};
#[must_use = "strategies do nothing unless used"]
#[derive(Clone, Co... | Self {
strategy,
_marker: PhantomData,
}
}
}
pub struct ArrayValueTree<T> {
tree: T,
shrinker: usize,
last_shrinker: Option<usize>,
}
impl<T, S, const LANES: usize> Strategy for UniformArrayStrategy<S, [T; LANES]>
where
T: core::fmt::Debug,
S: Strategy<V... | impl<S, T> UniformArrayStrategy<S, T> {
pub const fn new(strategy: S) -> Self { | random_line_split |
array.rs | //! Generic-length array strategy.
// Adapted from proptest's array code
// Copyright 2017 Jason Lingle
use core::{marker::PhantomData, mem::MaybeUninit};
use proptest::{
strategy::{NewTree, Strategy, ValueTree},
test_runner::TestRunner,
};
#[must_use = "strategies do nothing unless used"]
#[derive(Clone, Co... |
}
pub struct ArrayValueTree<T> {
tree: T,
shrinker: usize,
last_shrinker: Option<usize>,
}
impl<T, S, const LANES: usize> Strategy for UniformArrayStrategy<S, [T; LANES]>
where
T: core::fmt::Debug,
S: Strategy<Value = T>,
{
type Tree = ArrayValueTree<[S::Tree; LANES]>;
type Value = [T; LA... | {
Self {
strategy,
_marker: PhantomData,
}
} | identifier_body |
array.rs | //! Generic-length array strategy.
// Adapted from proptest's array code
// Copyright 2017 Jason Lingle
use core::{marker::PhantomData, mem::MaybeUninit};
use proptest::{
strategy::{NewTree, Strategy, ValueTree},
test_runner::TestRunner,
};
#[must_use = "strategies do nothing unless used"]
#[derive(Clone, Co... | <S, T> {
strategy: S,
_marker: PhantomData<T>,
}
impl<S, T> UniformArrayStrategy<S, T> {
pub const fn new(strategy: S) -> Self {
Self {
strategy,
_marker: PhantomData,
}
}
}
pub struct ArrayValueTree<T> {
tree: T,
shrinker: usize,
last_shrinker: Opti... | UniformArrayStrategy | identifier_name |
array.rs | //! Generic-length array strategy.
// Adapted from proptest's array code
// Copyright 2017 Jason Lingle
use core::{marker::PhantomData, mem::MaybeUninit};
use proptest::{
strategy::{NewTree, Strategy, ValueTree},
test_runner::TestRunner,
};
#[must_use = "strategies do nothing unless used"]
#[derive(Clone, Co... | else {
false
}
}
}
| {
self.shrinker = shrinker;
if self.tree[shrinker].complicate() {
true
} else {
self.last_shrinker = None;
false
}
} | conditional_block |
set_pusher.rs | //! [POST /_matrix/client/r0/pushers/set](https://matrix.org/docs/spec/client_server/r0.6.0#post-matrix-client-r0-pushers-set)
use ruma_api::ruma_api;
use super::Pusher;
ruma_api! {
metadata {
description: "This endpoint allows the creation, modification and deletion of pushers for this user ID.",
... |
request {
/// The pusher to configure
#[serde(flatten)]
pub pusher: Pusher,
/// Controls if another pusher with the same pushkey and app id should be created.
/// See the spec for details.
#[serde(default)]
pub append: bool
}
response {}
error... | rate_limited: true,
requires_authentication: true,
} | random_line_split |
lib.rs | //! rimd is a set of utilities to deal with midi messages and standard
//! midi files (SMF). It handles both standard midi messages and the meta
//! messages that are found in SMFs.
//!
//! rimd is fairly low level, and messages are stored and accessed in
//! their underlying format (i.e. a vector of u8s). There are... | {
Midi(MidiMessage),
Meta(MetaEvent),
}
impl fmt::Display for Event {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Event::Midi(ref m) => { write!(f, "{}", m) }
Event::Meta(ref m) => { write!(f, "{}", m) }
}
}
}
impl Event {
/// Retur... | Event | identifier_name |
lib.rs | //! rimd is a set of utilities to deal with midi messages and standard
//! midi files (SMF). It handles both standard midi messages and the meta
//! messages that are found in SMFs.
//!
//! rimd is fairly low level, and messages are stored and accessed in
//! their underlying format (i.e. a vector of u8s). There are... | fn from(err: MetaError) -> SMFError {
SMFError::MetaError(err)
}
}
impl From<FromUtf8Error> for SMFError {
fn from(_: FromUtf8Error) -> SMFError {
SMFError::InvalidSMFFile("Invalid UTF8 data in file")
}
}
impl error::Error for SMFError {
fn description(&self) -> &str {
matc... |
impl From<MetaError> for SMFError { | random_line_split |
lib.rs | //! rimd is a set of utilities to deal with midi messages and standard
//! midi files (SMF). It handles both standard midi messages and the meta
//! messages that are found in SMFs.
//!
//! rimd is fairly low level, and messages are stored and accessed in
//! their underlying format (i.e. a vector of u8s). There are... |
}
impl From<FromUtf8Error> for SMFError {
fn from(_: FromUtf8Error) -> SMFError {
SMFError::InvalidSMFFile("Invalid UTF8 data in file")
}
}
impl error::Error for SMFError {
fn description(&self) -> &str {
match *self {
SMFError::InvalidSMFFile(_) => "The SMF file was invalid",... | {
SMFError::MetaError(err)
} | identifier_body |
configuration.rs | //! Konfiguration Datei Managment
//!
use errors::*;
use std::fs::File;
use std::path::Path;
use std::io::Read;
pub struct Configuration;
impl Configuration {
/// Liest die Konfiguration
///
/// # Return values
///
/// Diese Funktion liefert ein Result. Das Result enthält die Konfiguration, als S... | ) -> Result<String> {
// TODO: In production nur Konfig von `/boot` verwenden!
let possible_paths = vec![
Path::new("/boot/xMZ-Mod-Touch.json"),
Path::new("/usr/share/xmz-mod-touch-server/xMZ-Mod-Touch.json.production"),
Path::new("xMZ-Mod-Touch.json"),
];
... | et_config( | identifier_name |
configuration.rs | //! Konfiguration Datei Managment
//!
use errors::*;
use std::fs::File;
use std::path::Path;
use std::io::Read;
pub struct Configuration;
impl Configuration {
/// Liest die Konfiguration
///
/// # Return values
///
/// Diese Funktion liefert ein Result. Das Result enthält die Konfiguration, als S... | }
Ok(ret)
}
}
|
match File::open(&p) {
Ok(mut file) => {
println!("Verwende Konfigurationsdatei: {}", p.display());
file.read_to_string(&mut ret)?;
}
Err(_) => panic!("Could not open file: {}", p.display()),
... | conditional_block |
configuration.rs | //! Konfiguration Datei Managment
//!
use errors::*;
use std::fs::File;
use std::path::Path;
use std::io::Read;
pub struct Configuration;
impl Configuration {
/// Liest die Konfiguration
///
/// # Return values
///
/// Diese Funktion liefert ein Result. Das Result enthält die Konfiguration, als S... | }
} | random_line_split | |
get_last_with_len.rs | //! lint on using `x.get(x.len() - 1)` instead of `x.last()`
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::SpanlessEq;
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Appli... | lhs,
rhs,
) = &get_index_arg.kind;
// LHS of subtraction is "x.len()"
if let ExprKind::MethodCall(arg_lhs_path, _, lhs_args, _) = &lhs.kind;
if arg_lhs_path.ident.name == sym::len;
if let Some(arg_lhs_struct) = lhs_args.get(0);... | {
if_chain! {
// Is a method call
if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
// Method name is "get"
if path.ident.name == sym!(get);
// Argument 0 (the struct we're calling the method on) is a vector
if let Some(struct_ca... | identifier_body |
get_last_with_len.rs | //! lint on using `x.get(x.len() - 1)` instead of `x.last()`
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::SpanlessEq;
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Appli... | fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if_chain! {
// Is a method call
if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
// Method name is "get"
if path.ident.name == sym!(get);
// Argument 0 (the struct... | }
declare_lint_pass!(GetLastWithLen => [GET_LAST_WITH_LEN]);
impl<'tcx> LateLintPass<'tcx> for GetLastWithLen { | random_line_split |
get_last_with_len.rs | //! lint on using `x.get(x.len() - 1)` instead of `x.last()`
use clippy_utils::diagnostics::span_lint_and_sugg;
use clippy_utils::source::snippet_with_applicability;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::SpanlessEq;
use if_chain::if_chain;
use rustc_ast::ast::LitKind;
use rustc_errors::Appli... | (&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if_chain! {
// Is a method call
if let ExprKind::MethodCall(path, _, args, _) = expr.kind;
// Method name is "get"
if path.ident.name == sym!(get);
// Argument 0 (the struct we're calling th... | check_expr | identifier_name |
svh-a-change-type-arg.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 ... | 4
} | random_line_split | |
svh-a-change-type-arg.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 ... | {
4
} | identifier_body | |
svh-a-change-type-arg.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T:U>(_: i32) -> int {
3
}
pub fn an_unused_name() -> int {
4
}
| foo | identifier_name |
input.pp.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 y /* 61#0 */() { }
| { let x /* 59#2 */ = 1; y /* 61#4 */ + x /* 59#5 */ } | identifier_body |
input.pp.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 ... | // minimal junk
#![feature(no_core)]
#![no_core]
macro_rules! foo /* 60#0 */(( $ x : ident ) => { y + $ x });
fn bar /* 62#0 */() { let x /* 59#2 */ = 1; y /* 61#4 */ + x /* 59#5 */ }
fn y /* 61#0 */() { } | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
input.pp.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 ... | /* 62#0 */() { let x /* 59#2 */ = 1; y /* 61#4 */ + x /* 59#5 */ }
fn y /* 61#0 */() { }
| bar | identifier_name |
rec.rs | use super::Fibonacci;
pub struct | ;
impl Fibonacci for &Recursive {
fn fib(self, n: u64) -> u64 {
if n == 0 || n == 1 {
1
} else {
self.fib(n - 1) + self.fib(n - 2)
}
}
}
#[cfg(test)]
mod tests {
use super::super::Fibonacci;
use super::Recursive;
macro_rules! fib_test {
($na... | Recursive | identifier_name |
rec.rs | use super::Fibonacci;
pub struct Recursive;
impl Fibonacci for &Recursive {
fn fib(self, n: u64) -> u64 {
if n == 0 || n == 1 {
1
} else {
self.fib(n - 1) + self.fib(n - 2)
}
}
}
#[cfg(test)]
mod tests {
use super::super::Fibonacci;
use super::Recursive... | fib_test!(two, 2, 2);
fib_test!(three, 3, 3);
} |
fib_test!(zero, 0, 1);
fib_test!(one, 1, 1); | random_line_split |
rec.rs | use super::Fibonacci;
pub struct Recursive;
impl Fibonacci for &Recursive {
fn fib(self, n: u64) -> u64 {
if n == 0 || n == 1 | else {
self.fib(n - 1) + self.fib(n - 2)
}
}
}
#[cfg(test)]
mod tests {
use super::super::Fibonacci;
use super::Recursive;
macro_rules! fib_test {
($name:ident, $($i:expr, $e:expr),+) => {
#[test]
fn $name() {
let r = Recursive;
... | {
1
} | conditional_block |
macro-pat.rs | // Copyright 2012-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... | mypat!() => 2,
_ => 3,
}
}
pub fn main() {
assert_eq!(1u, f(Some('x')));
assert_eq!(2u, f(Some('y')));
assert_eq!(3u, f(None));
assert_eq!(1, match Some('x') {
Some(char_x!()) => 1,
_ => 2,
});
assert_eq!(1, match Some('x') {
some!(char_x!()) => 1,
... | Some('x') => 1, | random_line_split |
macro-pat.rs | // Copyright 2012-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... | assert_eq!(3, {
let ident_pat!(x) = 2;
x+1
});
}
| {
assert_eq!(1u, f(Some('x')));
assert_eq!(2u, f(Some('y')));
assert_eq!(3u, f(None));
assert_eq!(1, match Some('x') {
Some(char_x!()) => 1,
_ => 2,
});
assert_eq!(1, match Some('x') {
some!(char_x!()) => 1,
_ => 2,
});
assert_eq!(1, match Some('x') {
... | identifier_body |
macro-pat.rs | // Copyright 2012-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... | (c: Option<char>) -> uint {
match c {
Some('x') => 1,
mypat!() => 2,
_ => 3,
}
}
pub fn main() {
assert_eq!(1u, f(Some('x')));
assert_eq!(2u, f(Some('y')));
assert_eq!(3u, f(None));
assert_eq!(1, match Some('x') {
Some(char_x!()) => 1,
_ => 2,
});
... | f | identifier_name |
error.rs | // Copyright 2015-2017 Parity Technologies
//
// 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 ... | (&self) -> &str {
"builder error"
}
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
| description | identifier_name |
error.rs | // Copyright 2015-2017 Parity Technologies
//
// 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 ... |
#[derive(Debug, PartialEq, Eq)]
/// Error concerning the RLP decoder.
pub enum DecoderError {
/// Data has additional bytes at the end of the valid RLP fragment.
RlpIsTooBig,
/// Data has too few bytes for valid RLP.
RlpIsTooShort,
/// Expect an encoded list, RLP was something else.
RlpExpectedToBeList,
/// Exp... | random_line_split | |
utility.rs | // Copyright 2016 Kyle Mayes
//
// 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 in w... | let end = self.get_last_span();
let delimited = Delimited {
delim: delim,
open_span: start,
tts: try!(tts),
close_span: end,
};
Ok((span_spans(start, end), delimited))
}
pub fn parse_token(&mut self, name: &str) -> PluginResult<(Sp... | let tts = self.apply(|p| {
let sep = SeqSep { sep: None, trailing_sep_allowed: false };
p.parse_seq_to_end(&Token::CloseDelim(delim), sep, |p| p.parse_token_tree())
}).1.map_err(|mut err| { err.cancel(); SaveEmitter::get_error() }); | random_line_split |
utility.rs | // Copyright 2016 Kyle Mayes
//
// 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 in w... | (&mut self, name: &str) -> PluginResult<(Span, Delimited)> {
let (start, delim) = match try!(self.next_token("opening delimiter", Some(name))) {
(span, Token::OpenDelim(delim)) => (span, delim),
(span, _) => return Err((span, "expected opening delimiter".into())),
};
let ... | parse_delim | identifier_name |
utility.rs | // Copyright 2016 Kyle Mayes
//
// 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 in w... |
/// Creates a new transaction which saves the current state of this parser.
pub fn transaction(&self) -> Transaction {
Transaction(self.index)
}
/// Returns a parsing error.
fn get_error(&self, mut span: Span, description: &str, name: Option<&str>) -> (Span, String) {
let mut mess... | {
if self.is_eof() {
None
} else {
Some(span_spans(self.get_span(), self.span))
}
} | identifier_body |
main.rs | extern crate rand;
use std::io;
use rand::Rng; // provide a random number generator
use std::cmp::Ordering;
fn | () {
let lower_bound = 1;
let upper_bound = 101;
println!("Guess the num! {} ~ {}", lower_bound, upper_bound);
let secret = rand::thread_rng() // get a copy of the rng
.gen_range(lower_bound, upper_bound);
// println!("The secret num is: {}", secret);
loop {
let mut guess = Stri... | main | identifier_name |
main.rs | extern crate rand;
use std::io;
use rand::Rng; // provide a random number generator
use std::cmp::Ordering;
fn main() | Err(_) => {
println!("Please Enter a number!\n");
continue;
}
};
println!("You guessed: {}", guess);
match guess.cmp(&secret) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too bi... | {
let lower_bound = 1;
let upper_bound = 101;
println!("Guess the num! {} ~ {}", lower_bound, upper_bound);
let secret = rand::thread_rng() // get a copy of the rng
.gen_range(lower_bound, upper_bound);
// println!("The secret num is: {}", secret);
loop {
let mut guess = String... | identifier_body |
main.rs | extern crate rand;
use std::io;
use rand::Rng; // provide a random number generator
use std::cmp::Ordering;
fn main() {
let lower_bound = 1;
let upper_bound = 101;
println!("Guess the num! {} ~ {}", lower_bound, upper_bound);
let secret = rand::thread_rng() // get a copy of the rng
.gen_range(... |
};
println!("You guessed: {}", guess);
match guess.cmp(&secret) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}... | {
println!("Please Enter a number!\n");
continue;
} | conditional_block |
main.rs | extern crate rand;
use std::io;
use rand::Rng; // provide a random number generator
use std::cmp::Ordering;
fn main() {
let lower_bound = 1;
let upper_bound = 101;
println!("Guess the num! {} ~ {}", lower_bound, upper_bound);
let secret = rand::thread_rng() // get a copy of the rng
.gen_range(... | Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
} | println!("You guessed: {}", guess);
match guess.cmp(&secret) { | random_line_split |
main.rs | extern crate tcod;
extern crate rand;
use std::cmp;
use tcod::console::*;
use tcod::colors::{self, Color};
use rand::Rng;
// Actual size of the window
const SCREEN_WIDTH: i32 = 80;
const SCREEN_HEIGHT: i32 = 50;
// Size of the map in the window
const MAP_WIDTH: i32 = 80;
const MAP_HEIGHT: i32 = 45;
// Parameters ... | (&self, con: &mut Console)
{
con.set_default_foreground(self.color);
con.put_char(self.x, self.y, self.char, BackgroundFlag::None);
}
pub fn clear(&self, con: &mut Console)
{
con.put_char(self.x, self.y,'', BackgroundFlag::None)
}
}
fn create_room(room: Rect, map: &mut Map)... | draw | identifier_name |
main.rs | extern crate tcod;
extern crate rand;
use std::cmp;
use tcod::console::*;
use tcod::colors::{self, Color};
use rand::Rng;
// Actual size of the window
const SCREEN_WIDTH: i32 = 80;
const SCREEN_HEIGHT: i32 = 50;
// Size of the map in the window
const MAP_WIDTH: i32 = 80;
const MAP_HEIGHT: i32 = 45;
// Parameters ... | pub fn clear(&self, con: &mut Console)
{
con.put_char(self.x, self.y,'', BackgroundFlag::None)
}
}
fn create_room(room: Rect, map: &mut Map) {
for x in (room.x1 + 1)..room.x2 {
for y in (room.y1 + 1)..room.y2 {
map[x as usize][y as usize] = Tile::empty();
}
}
}
... | con.put_char(self.x, self.y, self.char, BackgroundFlag::None);
}
| random_line_split |
main.rs | extern crate tcod;
extern crate rand;
use std::cmp;
use tcod::console::*;
use tcod::colors::{self, Color};
use rand::Rng;
// Actual size of the window
const SCREEN_WIDTH: i32 = 80;
const SCREEN_HEIGHT: i32 = 50;
// Size of the map in the window
const MAP_WIDTH: i32 = 80;
const MAP_HEIGHT: i32 = 45;
// Parameters ... | else {
con.set_char_background(x, y, COLOR_DARK_GROUND, BackgroundFlag::Set);
}
}
}
for object in objects {
object.draw(con);
}
blit (con, (0,0), (MAP_WIDTH, MAP_HEIGHT), root, (0,0), 1.0, 1.0);
}
fn handle_keys(root: &mut Root, player: &mut Object, map:... | {
con.set_char_background(x, y, COLOR_DARK_WALL, BackgroundFlag::Set);
} | conditional_block |
timeout.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 ... |
}
#[unsafe_destructor]
impl<T> Drop for AccessTimeout<T> {
fn drop(&mut self) {
match self.timer {
Some(ref timer) => unsafe {
let data = uvll::get_data_for_uv_handle(timer.handle);
let _data: Box<TimerContext> = mem::transmute(data);
},
... | {
match *self.state {
TimeoutPending(NoWaiter) | TimeoutPending(AccessPending) =>
unreachable!(),
NoTimeout | TimedOut => {}
TimeoutPending(RequestPending) => {
*self.state = TimeoutPending(NoWaiter);
}
}
} | identifier_body |
timeout.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 ... | (&mut self) {
match *self.state {
TimeoutPending(NoWaiter) | TimeoutPending(AccessPending) =>
unreachable!(),
NoTimeout | TimedOut => {}
TimeoutPending(RequestPending) => {
*self.state = TimeoutPending(NoWaiter);
}
}
}
... | drop | identifier_name |
timeout.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 ... | match self.timer {
Some(ref timer) => unsafe {
let data = uvll::get_data_for_uv_handle(timer.handle);
let _data: Box<TimerContext> = mem::transmute(data);
},
None => {}
}
}
}
////////////////////////////////////////////////////////... | random_line_split | |
login.rs | use command_prelude::*;
use std::io::{self, BufRead};
use cargo::core::{Source, SourceId};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CargoResultExt};
use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
... | .unwrap_or(config.api.unwrap())
}
};
println!("please visit {}me and paste the API Token below", host);
let mut line = String::new();
let input = io::stdin();
input
.lock()
.read_line(&mut li... | {
let registry = args.registry(config)?;
let token = match args.value_of("token") {
Some(token) => token.to_string(),
None => {
let host = match registry {
Some(ref _registry) => {
return Err(format_err!(
"token must be pro... | identifier_body |
login.rs | use command_prelude::*;
use std::io::{self, BufRead};
use cargo::core::{Source, SourceId};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CargoResultExt};
use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
... | (config: &mut Config, args: &ArgMatches) -> CliResult {
let registry = args.registry(config)?;
let token = match args.value_of("token") {
Some(token) => token.to_string(),
None => {
let host = match registry {
Some(ref _registry) => {
return Err(f... | exec | identifier_name |
login.rs | use command_prelude::*;
use std::io::{self, BufRead};
use cargo::core::{Source, SourceId}; | use cargo::ops;
pub fn cli() -> App {
subcommand("login")
.about(
"Save an api token from the registry locally. \
If token is not specified, it will be read from stdin.",
)
.arg(Arg::with_name("token"))
.arg(opt("host", "Host to set the token for").value_name("... | use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CargoResultExt}; | random_line_split |
abi.rs | use std::{fmt::Debug, result::Result};
use wasm_bindgen::{
convert::FromWasmAbi,
describe::{inform, WasmDescribe},
JsValue,
};
pub type JsResult<T> = Result<T, JsValue>;
pub trait Context<T> {
fn context(self, msg: &dyn Debug) -> JsResult<T>;
}
impl<T, TError> Context<T> for Result<T, TError>
where
... | 2 => LogLevel(log::Level::Info),
3 => LogLevel(log::Level::Warn),
_ => LogLevel(log::Level::Error),
}
}
} | 0 => LogLevel(log::Level::Trace),
1 => LogLevel(log::Level::Debug), | random_line_split |
abi.rs | use std::{fmt::Debug, result::Result};
use wasm_bindgen::{
convert::FromWasmAbi,
describe::{inform, WasmDescribe},
JsValue,
};
pub type JsResult<T> = Result<T, JsValue>;
pub trait Context<T> {
fn context(self, msg: &dyn Debug) -> JsResult<T>;
}
impl<T, TError> Context<T> for Result<T, TError>
where
... |
}
pub struct LogLevel(pub log::Level);
impl WasmDescribe for LogLevel {
fn describe() {
inform(wasm_bindgen::describe::I8);
}
}
impl FromWasmAbi for LogLevel {
type Abi = u32;
unsafe fn from_abi(js: Self::Abi) -> Self {
match js {
0 => LogLevel(log::Level::Trace),
... | {
match self {
Ok(v) => Ok(v),
Err(err) => Err(format!("{:?} {:?}", msg, err).into()),
}
} | identifier_body |
abi.rs | use std::{fmt::Debug, result::Result};
use wasm_bindgen::{
convert::FromWasmAbi,
describe::{inform, WasmDescribe},
JsValue,
};
pub type JsResult<T> = Result<T, JsValue>;
pub trait Context<T> {
fn context(self, msg: &dyn Debug) -> JsResult<T>;
}
impl<T, TError> Context<T> for Result<T, TError>
where
... | (self, msg: &dyn Debug) -> JsResult<T> {
match self {
Ok(v) => Ok(v),
Err(err) => Err(format!("{:?} {:?}", msg, err).into()),
}
}
}
pub struct LogLevel(pub log::Level);
impl WasmDescribe for LogLevel {
fn describe() {
inform(wasm_bindgen::describe::I8);
}
}
... | context | identifier_name |
map.rs | use std::ops::Range;
use cgmath::{Vector3, InnerSpace, Zero};
use noise::{BasicMulti, Seedable, NoiseModule};
use spherical_voronoi as sv;
use rand::{thread_rng, Rng, Rand};
use color::Color;
use ideal::{IdVec, IdsIter};
use settings;
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum CornerK... |
}
for corner in map.corners() {
let elevation = {
let regions = map.corner_regions(corner);
let len = regions.len() as f64;
regions.iter().map(|®ion| map.region_elevation(region)).sum::<f64>() / len
};
map.corners[co... | {
map.regions[region].biome = self.sea;
} | conditional_block |
map.rs | use std::ops::Range;
use cgmath::{Vector3, InnerSpace, Zero};
use noise::{BasicMulti, Seedable, NoiseModule};
use spherical_voronoi as sv;
use rand::{thread_rng, Rng, Rand};
use color::Color;
use ideal::{IdVec, IdsIter};
use settings;
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum CornerK... | {
regions: Vec<Region>,
position: Vector3<f64>,
kind: CornerKind,
elevation: f64,
}
create_id!(Corner);
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum BorderKind {
River,
Coast,
None,
}
#[derive(Clone)]
#[derive(Serialize, Deserialize)]
pub struct BorderData ... | CornerData | identifier_name |
map.rs | use std::ops::Range;
use cgmath::{Vector3, InnerSpace, Zero};
use noise::{BasicMulti, Seedable, NoiseModule};
use spherical_voronoi as sv;
use rand::{thread_rng, Rng, Rand};
use color::Color;
use ideal::{IdVec, IdsIter};
use settings;
#[derive(Copy, Clone, PartialEq)]
#[derive(Serialize, Deserialize)]
pub enum CornerK... | borders: &'a IdVec<Border, BorderData>,
region: Region,
inner: ::std::slice::Iter<'b, Border>,
}
impl<'a, 'b> ::std::iter::Iterator for Neighbors<'a, 'b> {
type Item = Region;
fn next(&mut self) -> Option<Self::Item> {
if let Some(border) = self.inner.next() {
let (region0, reg... | }
pub struct Neighbors<'a, 'b> { | random_line_split |
lib.rs | //! This crate provides the basic environments for Kailua.
//!
//! * Location types ([`Unit`](./struct.Unit.html), [`Pos`](./struct.Pos.html),
//! [`Span`](./struct.Span.html)) and a location-bundled container | //!
//! * The resolver for locations
//! ([`kailua_env::source`](./source/index.html))
//!
//! * An arbitrary mapping from location ranges to values
//! ([`kailua_env::spanmap`](./spanmap/index.html))
mod loc;
pub mod scope;
pub mod source;
pub mod spanmap;
pub use loc::{Unit, Pos, Span, Spanned, WithLoc};
pub us... | //! ([`Spanned`](./struct.Spanned.html))
//!
//! * Scope identifiers and a location-to-scope map
//! ([`kailua_env::scope`](./scope/index.html)) | random_line_split |
extensions.rs | use serde::{Deserialize, Serialize, Serializer};
use std::convert::From;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
p... |
}
impl From<bool> for ExtensionValue {
fn from(s: bool) -> Self {
ExtensionValue::Boolean(s)
}
}
impl From<i64> for ExtensionValue {
fn from(s: i64) -> Self {
ExtensionValue::Integer(s)
}
}
impl ExtensionValue {
pub fn from_string<S>(s: S) -> Self
where
S: Into<String... | {
ExtensionValue::String(s)
} | identifier_body |
extensions.rs | use serde::{Deserialize, Serialize, Serializer};
use std::convert::From;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
p... | (s: String) -> Self {
ExtensionValue::String(s)
}
}
impl From<bool> for ExtensionValue {
fn from(s: bool) -> Self {
ExtensionValue::Boolean(s)
}
}
impl From<i64> for ExtensionValue {
fn from(s: i64) -> Self {
ExtensionValue::Integer(s)
}
}
impl ExtensionValue {
pub fn ... | from | identifier_name |
extensions.rs | use std::convert::From;
use std::fmt;
#[derive(PartialEq, Eq, Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
/// Represents all the possible [CloudEvents extension](https://github.com/cloudevents/spec/blob/master/spec.md#extension-context-attributes) values
pub enum ExtensionValue {
/// Represents a [`S... | use serde::{Deserialize, Serialize, Serializer}; | random_line_split | |
issue-7867.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() {
match (true, false) {
A::B => (), //~ ERROR expected `(bool, bool)`, found `A` (expected tuple, found enum A)
_ => ()
}
match &Some(42i) {
Some(x) => (), //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`... | {} | identifier_body |
issue-7867.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() {
match (true, false) {
A::B => (), //~ ERROR expected `(bool, bool)`, found `A` (expected tuple, found enum A)
_ => ()
}
match &Some(42i) {
Some(x) => (), //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Optio... | bar | identifier_name |
issue-7867.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 ... | match (true, false) {
A::B => (), //~ ERROR expected `(bool, bool)`, found `A` (expected tuple, found enum A)
_ => ()
}
match &Some(42i) {
Some(x) => (), //~ ERROR expected `&core::option::Option<int>`,
// found `core::option::Option<_>`
None =>... | enum A { B, C }
mod foo { pub fn bar() {} }
fn main() { | random_line_split |
asm-target-clobbers.rs | // only-x86_64
// revisions: base avx512
// [avx512]compile-flags: -C target-feature=+avx512f
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @avx512_clobber
// base: call void asm sideeffect inteldialect "", "~{xmm31}"()
// avx512: call float asm sideeffect inteldialect "", "=&{xmm31}"()
#[no_mangle]
pub un... |
// CHECK-LABEL: @eax_clobber
// CHECK: call i32 asm sideeffect inteldialect "", "=&{ax}"()
#[no_mangle]
pub unsafe fn eax_clobber() {
asm!("", out("eax") _, options(nostack, nomem, preserves_flags));
}
| {
asm!("", out("zmm31") _, options(nostack, nomem, preserves_flags));
} | identifier_body |
asm-target-clobbers.rs | // only-x86_64
// revisions: base avx512
// [avx512]compile-flags: -C target-feature=+avx512f
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @avx512_clobber
// base: call void asm sideeffect inteldialect "", "~{xmm31}"()
// avx512: call float asm sideeffect inteldialect "", "=&{xmm31}"()
#[no_mangle]
pub un... | () {
asm!("", out("zmm31") _, options(nostack, nomem, preserves_flags));
}
// CHECK-LABEL: @eax_clobber
// CHECK: call i32 asm sideeffect inteldialect "", "=&{ax}"()
#[no_mangle]
pub unsafe fn eax_clobber() {
asm!("", out("eax") _, options(nostack, nomem, preserves_flags));
}
| avx512_clobber | identifier_name |
asm-target-clobbers.rs | // only-x86_64
// revisions: base avx512
// [avx512]compile-flags: -C target-feature=+avx512f
#![crate_type = "rlib"]
#![feature(asm)]
// CHECK-LABEL: @avx512_clobber
// base: call void asm sideeffect inteldialect "", "~{xmm31}"() | pub unsafe fn avx512_clobber() {
asm!("", out("zmm31") _, options(nostack, nomem, preserves_flags));
}
// CHECK-LABEL: @eax_clobber
// CHECK: call i32 asm sideeffect inteldialect "", "=&{ax}"()
#[no_mangle]
pub unsafe fn eax_clobber() {
asm!("", out("eax") _, options(nostack, nomem, preserves_flags));
} | // avx512: call float asm sideeffect inteldialect "", "=&{xmm31}"()
#[no_mangle] | random_line_split |
ecies_hkdf_recipient_kem.rs | // Copyright 2021 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | <'a> {
recipient_private_key: &'a EcPrivateKey,
}
impl<'a> EciesHkdfRecipientKem<'a> {
pub fn new(priv_key: &'a EcPrivateKey) -> Self {
Self {
recipient_private_key: priv_key,
}
}
/// Uses the KEM to generate a new HKDF-based key.
pub(crate) fn decapsulate(
&sel... | EciesHkdfRecipientKem | identifier_name |
ecies_hkdf_recipient_kem.rs | // Copyright 2021 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | recipient_private_key: priv_key,
}
}
/// Uses the KEM to generate a new HKDF-based key.
pub(crate) fn decapsulate(
&self,
kem: &[u8],
hash_alg: HashType,
salt: &[u8],
info: &[u8],
key_size: usize,
point_format: EcPointFormat,
)... | random_line_split | |
ecies_hkdf_recipient_kem.rs | // Copyright 2021 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
}
| {
let pub_point = subtle::point_decode(
self.recipient_private_key.public_key().curve(),
point_format,
kem,
)?;
let secret = subtle::compute_shared_secret(&pub_point, self.recipient_private_key)?;
let mut i = kem.to_vec();
i.extend_from_slice(&... | identifier_body |
year.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | None => {
NaiveDate::from_ymd(now.year() + 1, 1, 1).and_hms(0, 0, 0)
},
Some(Ok(dt)) => dt,
Some(Err(e)) => {
trace_error(&e);
return 1
}
};
let tags = cmd
.values_of("tags")
... | {
let cmd = rt.cli().subcommand().1.unwrap(); // checked in main
let filter = {
use chrono::offset::Local;
use chrono::naive::NaiveDate;
use chrono::Datelike;
let now = Local::now();
let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) ... | identifier_body |
year.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... |
};
let end = match cmd.value_of("end").map(::chrono::naive::NaiveDateTime::from_str) {
None => {
NaiveDate::from_ymd(now.year() + 1, 1, 1).and_hms(0, 0, 0)
},
Some(Ok(dt)) => dt,
Some(Err(e)) => {
trace_error(&e);
... | {
trace_error(&e);
return 1
} | conditional_block |
year.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | (rt: &Runtime) -> i32 {
let cmd = rt.cli().subcommand().1.unwrap(); // checked in main
let filter = {
use chrono::offset::Local;
use chrono::naive::NaiveDate;
use chrono::Datelike;
let now = Local::now();
let start = match cmd.value_of("start").map(::chrono::naive::Nai... | year | identifier_name |
year.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | let start = match cmd.value_of("start").map(::chrono::naive::NaiveDateTime::from_str) {
None => NaiveDate::from_ymd(now.year(), 1, 1).and_hms(0, 0, 0),
Some(Ok(dt)) => dt,
Some(Err(e)) => {
trace_error(&e);
return 1
}
};
... | use chrono::naive::NaiveDate;
use chrono::Datelike;
let now = Local::now();
| random_line_split |
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 ipc_channel;
extern crate msg;
#[macro_use]
extern crate serde_derive;
pub ext... | pub use webvr::VRStageParameters as WebVRStageParameters;
pub use webvr_traits::{WebVRMsg, WebVRResult}; | pub use webvr::VRPose as WebVRPose; | random_line_split |
os_release.rs | use std::fs;
pub enum OsReleaseId {
Amazon,
CentOs,
Debian,
Ubuntu,
}
const OS_RELEASE_PATH: &str = "/etc/os-release";
impl OsReleaseId {
fn from_os_release_str(s: &str) -> Option<Self> {
let id_line = s.lines().find(|l| l.starts_with("ID="))?; | let id = id_line.trim_start_matches("ID=").trim_matches('"');
match id {
"amzn" => Some(OsReleaseId::Amazon),
"centos" => Some(OsReleaseId::CentOs),
"debian" => Some(OsReleaseId::Debian),
"ubuntu" => Some(OsReleaseId::Ubuntu),
_ => None,
... | random_line_split | |
os_release.rs | use std::fs;
pub enum OsReleaseId {
Amazon,
CentOs,
Debian,
Ubuntu,
}
const OS_RELEASE_PATH: &str = "/etc/os-release";
impl OsReleaseId {
fn from_os_release_str(s: &str) -> Option<Self> {
let id_line = s.lines().find(|l| l.starts_with("ID="))?;
let id = id_line.trim_start_matches(... | () -> Option<Self> {
fs::read_to_string(OS_RELEASE_PATH)
.ok()
.as_deref()
.and_then(Self::from_os_release_str)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_from_os_release() {
let actual =
OsReleaseId::from_os_release_st... | parse_os_release | identifier_name |
mpmc_bounded_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | let q = Queue::with_capacity(nthreads*nmsgs);
assert_eq!(None, q.pop());
let (tx, rx) = channel();
for _ in 0..nthreads {
let q = q.clone();
let tx = tx.clone();
thread::spawn(move || {
let q = q;
for i in 0..nmsgs {
... | #[test]
fn test() {
let nthreads = 8;
let nmsgs = 1000; | random_line_split |
mpmc_bounded_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | <T> {
state: Arc<State<T>>,
}
impl<T> State<T> {
fn with_capacity(capacity: usize) -> State<T> {
let capacity = if capacity < 2 || (capacity & (capacity - 1))!= 0 {
if capacity < 2 {
2
} else {
// use next power of 2 as capacity
ca... | Queue | identifier_name |
mpmc_bounded_queue.rs | /* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of con... | ,
Some(_) => {
i += 1;
if i == nmsgs { break }
}
}
}
tx.send(i).unwrap();
});
}
for rx in &mut completion_rxs {
assert_eq!(... | {} | conditional_block |
wrapper.rs | t a potentially non-trivial
/// performance cost) by implementing Drop and making LayoutFoo non-Copy.
#[derive(Clone, Copy)]
pub struct GeckoNode<'ln>(pub &'ln RawGeckoNode);
impl<'ln> fmt::Debug for GeckoNode<'ln> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(el) = self.as_element()... | fn first_child_element(&self) -> Option<Self> {
let mut child = self.as_node().first_child();
while let Some(child_node) = child {
if let Some(el) = child_node.as_element() {
return Some(el)
}
child = child_node.next_sibling();
}
None... | unsafe { bindings::Gecko_GetParentElement(self.0).map(GeckoElement) }
}
| identifier_body |
wrapper.rs | t a potentially non-trivial
/// performance cost) by implementing Drop and making LayoutFoo non-Copy.
#[derive(Clone, Copy)]
pub struct GeckoNode<'ln>(pub &'ln RawGeckoNode);
impl<'ln> fmt::Debug for GeckoNode<'ln> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(el) = self.as_element()... | NonTSPseudoClass::ReadOnly => {
!self.get_state().contains(pseudo_class.state_flag())
}
NonTSPseudoClass::MozBrowserFrame => unsafe {
Gecko_MatchesElement(pseudo_class.to_gecko_pseudoclasstype().unwrap(), self.0)
}
}
}
fn get... | self.get_state().contains(pseudo_class.state_flag())
},
| conditional_block |
wrapper.rs | // TODO(shinglyu): implement this in Gecko: https://github.com/servo/servo/pull/11890
true
}
// TODO(shinglyu): implement this in Gecko: https://github.com/servo/servo/pull/11890
unsafe fn set_dirty_on_viewport_size_changed(&self) {}
}
/// A wrapper on top of two kind of iterators, depending on ... | unsafe {
bindings::Gecko_AttrHasSuffix(self.0,
attr.ns_or_null(),
attr.select_name(self.is_html_element_in_html_document()),
value.as_ptr()) | random_line_split | |
wrapper.rs | a potentially non-trivial
/// performance cost) by implementing Drop and making LayoutFoo non-Copy.
#[derive(Clone, Copy)]
pub struct GeckoNode<'ln>(pub &'ln RawGeckoNode);
impl<'ln> fmt::Debug for GeckoNode<'ln> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let Some(el) = self.as_element() ... | lf) {
self.unset_flags(NODE_HAS_DIRTY_DESCENDANTS_FOR_SERVO as u32)
}
fn store_children_to_process(&self, _: isize) {
// This is only used for bottom-up traversal, and is thus a no-op for Gecko.
}
fn did_process_child(&self) -> isize {
panic!("Atomic child count not implemented... | t_dirty_descendants(&se | identifier_name |
extensions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::auth::csrf_token;
use iml_wire_types::{GroupType, Session};
use seed::{fetch, prelude::*, *};
/// Extension methods for the Session API object.
pub(crate) ... |
}
/// Allows for merging attributes onto an existing item
pub(crate) trait MergeAttrs {
fn merge_attrs(self, attrs: Attrs) -> Self;
}
impl MergeAttrs for Attrs {
fn merge_attrs(mut self, attrs: Attrs) -> Self {
self.merge(attrs);
self
}
}
impl<T> MergeAttrs for Node<T> {
fn merge_at... | {
match csrf_token() {
Some(csrf) => self.header("X-CSRFToken", &csrf),
None => self,
}
} | identifier_body |
extensions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::auth::csrf_token;
use iml_wire_types::{GroupType, Session};
use seed::{fetch, prelude::*, *};
/// Extension methods for the Session API object.
pub(crate) ... | fn graphql_query<T: serde::Serialize>(x: &T) -> Self;
fn with_auth(self: Self) -> Self;
}
impl RequestExt for fetch::Request {
fn api_call(path: impl ToString) -> Self {
Self::new(format!("/api/{}/", path.to_string()))
}
fn api_query(path: impl ToString, args: impl serde::Serialize) -> Resu... | pub(crate) trait RequestExt: Sized {
fn api_call(path: impl ToString) -> Self;
fn api_query(path: impl ToString, args: impl serde::Serialize) -> Result<Self, serde_urlencoded::ser::Error>;
fn api_item(path: impl ToString, item: impl ToString) -> Self; | random_line_split |
extensions.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use crate::auth::csrf_token;
use iml_wire_types::{GroupType, Session};
use seed::{fetch, prelude::*, *};
/// Extension methods for the Session API object.
pub(crate) ... | (mut self, attrs: Attrs) -> Self {
self.merge(attrs);
self
}
}
impl<T> MergeAttrs for Node<T> {
fn merge_attrs(self, attrs: Attrs) -> Self {
if let Self::Element(mut el) = self {
el.attrs.merge(attrs);
Self::Element(el)
} else {
self
... | merge_attrs | identifier_name |
ast.rs | use std::cell::Cell;
use std::fmt;
use std::vec::Vec;
pub type Var = String;
pub type Atom = String;
pub enum TopLevel {
Fact(Term),
Query(Term)
}
#[derive(Clone, Copy)]
pub enum Level {
Shallow, Deep
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
mat... | (&self) -> usize {
match self {
&Reg::ArgAndNorm(_, norm) | &Reg::Norm(norm) => norm
}
}
}
pub enum Term {
Atom(Cell<usize>, Atom),
Clause(Cell<usize>, Atom, Vec<Box<Term>>),
Var(Cell<Reg>, Var)
}
pub enum TermRef<'a> {
Atom(Level, &'a Cell<usize>, &'a Atom),
Clause... | norm | identifier_name |
ast.rs | use std::cell::Cell;
use std::fmt;
use std::vec::Vec;
pub type Var = String;
pub type Atom = String;
pub enum TopLevel {
Fact(Term),
Query(Term)
}
#[derive(Clone, Copy)]
pub enum Level {
Shallow, Deep
}
impl fmt::Display for Level {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
mat... | match self {
&Term::Atom(_, _) | &Term::Var(_, _) => 0,
&Term::Clause(_, _, ref child_terms) => child_terms.len()
}
}
} | random_line_split | |
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/.
//! A library for interacting with Twitter.
//!
//! [Repository](https://github.com/QuietMisdreavus/twitter-rs)
//!
/... | //!
//! ```rust,no_run
//! # use egg_mode::Token;
//! use egg_mode::tweet::DraftTweet;
//! # #[tokio::main]
//! # async fn main() {
//! # let token: Token = unimplemented!();
//!
//! let post = DraftTweet::new("Hey Twitter!").send(&token).await.unwrap();
//! # }
//! ```
//!
//! # Types and Functions
//!
//! All of the ... | //!
//! To post a new tweet: | random_line_split |
minimum_window_substring.rs | use std::collections::hash_map::Entry::Occupied;
use std::collections::HashMap;
struct Solution {}
impl Solution {
pub fn min_window(&self, s: String, t: String) -> String {
if s.len() < t.len() {
return String::from("");
}
let target_hm = t.chars().fold(HashMap::new(), |mut ac... |
#[test]
fn solution() {
let sol = Solution {};
assert_eq!(
sol.min_window(String::from("ADOBECODEBANC"), String::from("ABC")),
"BANC"
);
assert_eq!(sol.min_window(String::from(""), String::from("ABC")), "");
assert_eq!(sol.min_window(String::from(... |
#[cfg(test)]
mod tests {
use super::Solution; | random_line_split |
minimum_window_substring.rs | use std::collections::hash_map::Entry::Occupied;
use std::collections::HashMap;
struct Solution {}
impl Solution {
pub fn min_window(&self, s: String, t: String) -> String | let mut l_idx = 0 as usize;
let mut r_idx = 0 as usize;
while r_idx < filtered_s.len() {
let curr_char = filtered_s[r_idx];
*curr_hm.entry(curr_char.1).or_insert(0) += 1;
// we move the l_idx til we still have a complete set of letters with occurences
... | {
if s.len() < t.len() {
return String::from("");
}
let target_hm = t.chars().fold(HashMap::new(), |mut acc, c| {
*acc.entry(c).or_insert(0) += 1;
acc
});
let s_vec: Vec<char> = s.chars().collect();
let filtered_s: Vec<(usize, char)> =... | identifier_body |
minimum_window_substring.rs | use std::collections::hash_map::Entry::Occupied;
use std::collections::HashMap;
struct Solution {}
impl Solution {
pub fn min_window(&self, s: String, t: String) -> String {
if s.len() < t.len() {
return String::from("");
}
let target_hm = t.chars().fold(HashMap::new(), |mut ac... | () {
let sol = Solution {};
assert_eq!(
sol.min_window(String::from("ADOBECODEBANC"), String::from("ABC")),
"BANC"
);
assert_eq!(sol.min_window(String::from(""), String::from("ABC")), "");
assert_eq!(sol.min_window(String::from("RTY"), String::from("ABC"))... | solution | identifier_name |
small-enum-range-edge.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | { Lu = 0, Hu = 255 }
static CLu: Eu = Eu::Lu;
static CHu: Eu = Eu::Hu;
#[repr(i8)]
#[derive(Copy)]
enum Es { Ls = -128, Hs = 127 }
static CLs: Es = Es::Ls;
static CHs: Es = Es::Hs;
pub fn main() {
assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8);
assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8);
assert_eq!(CLu... | Eu | identifier_name |
small-enum-range-edge.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8);
assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8);
assert_eq!(CLu as u8, Eu::Lu as u8);
assert_eq!(CHu as u8, Eu::Hu as u8);
assert_eq!(CLs as i8, Es::Ls as i8);
assert_eq!(CHs as i8, Es::Hs as i8);
} | identifier_body | |
small-enum-range-edge.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | #[repr(u8)]
#[derive(Copy)]
enum Eu { Lu = 0, Hu = 255 }
static CLu: Eu = Eu::Lu;
static CHu: Eu = Eu::Hu;
#[repr(i8)]
#[derive(Copy)]
enum Es { Ls = -128, Hs = 127 }
static CLs: Es = Es::Ls;
static CHs: Es = Es::Hs;
pub fn main() {
assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8);
assert_eq!((Es::Hs as i8) + 1... | */
| random_line_split |
uio.rs | //! Vectored I/O
use crate::Result;
use crate::errno::Errno;
use libc::{self, c_int, c_void, size_t, off_t};
use std::marker::PhantomData;
use std::os::unix::io::RawFd;
/// Low-level vectored write to a raw file descriptor
///
/// See also [writev(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/writev.... | }, PhantomData)
}
}
impl<'a> IoVec<&'a mut [u8]> {
/// Create an `IoVec` from a mutable Rust slice.
pub fn from_mut_slice(buf: &'a mut [u8]) -> IoVec<&'a mut [u8]> {
IoVec(libc::iovec {
iov_base: buf.as_ptr() as *mut c_void,
iov_len: buf.len() as size_t,
}, P... | iov_base: buf.as_ptr() as *mut c_void,
iov_len: buf.len() as size_t, | random_line_split |
uio.rs | //! Vectored I/O
use crate::Result;
use crate::errno::Errno;
use libc::{self, c_int, c_void, size_t, off_t};
use std::marker::PhantomData;
use std::os::unix::io::RawFd;
/// Low-level vectored write to a raw file descriptor
///
/// See also [writev(2)](https://pubs.opengroup.org/onlinepubs/9699919799/functions/writev.... | (fd: RawFd, iov: &[IoVec<&[u8]>],
offset: off_t) -> Result<usize> {
#[cfg(target_env = "uclibc")]
let offset = offset as libc::off64_t; // uclibc doesn't use off_t
let res = unsafe {
libc::pwritev(fd, iov.as_ptr() as *const libc::iovec, iov.len() as c_int, offset)
};
Errno::r... | pwritev | identifier_name |
lib.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(warnings)]
// Enable all clippy lints except for many of the pedantic ones. It's a shame this needs to be copied and pasted across crates, but there doesn't appear to be a way to... | mod core;
mod externs;
mod interning;
mod intrinsics;
mod nodes;
mod scheduler;
mod selectors;
mod session;
mod tasks;
mod types;
pub use crate::context::{Core, ExecutionStrategyOptions, RemotingOptions};
pub use crate::core::{Failure, Function, Key, Params, TypeId, Value};
pub use crate::intrinsics::Intrinsics;
pub u... | mod context; | random_line_split |
pending.rs | /*
* Copyright (C) 2017 AltOS-Rust Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distribute... | (&self, hardware: Hardware) -> bool {
let interrupt = hardware as u8;
self.0 & (0b1 << interrupt)!= 0
}
}
impl ICPR {
pub fn clear_pending(&mut self, hardware: Hardware) {
let interrupt = hardware as u8;
self.0 |= 0b1 << interrupt;
}
}
#[cfg(test)]
mod tests {
use sup... | interrupt_is_pending | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.