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 |
|---|---|---|---|---|
trace.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/. */
//! Utilities for tracing JS-managed values.
//!
//! The lifetime of DOM objects is managed by the SpiderMonkey Ga... | // if e.trace() is a no-op (e.g it is an no_jsmanaged_fields type)
impl<T: JSTraceable> JSTraceable for Vec<T> {
#[inline]
fn trace(&self, trc: *mut JSTracer) {
for e in self.iter() {
e.trace(trc);
}
}
}
// XXXManishearth Check if the following three are optimized to no-ops
// i... | // XXXManishearth Check if the following three are optimized to no-ops | random_line_split |
debug_view.rs | use crate::logger;
use crate::theme;
use crate::view::View;
use crate::Printer;
use crate::Vec2;
use unicode_width::UnicodeWidthStr;
/// View used for debugging, showing logs.
pub struct DebugView {
// TODO: wrap log lines if needed, and save the line splits here.
}
impl DebugView {
/// Creates a new DebugVi... | // TODO: customizable time format? (24h/AM-PM)
printer.print(
(0, i),
&format!(
"{} | [ ] {}",
record.time.with_timezone(&chrono::Local).format("%T%.3f"),
record.message
),
... |
for (i, record) in logs.iter().skip(skipped).enumerate() {
// TODO: Apply style to message? (Ex: errors in bold?) | random_line_split |
debug_view.rs | use crate::logger;
use crate::theme;
use crate::view::View;
use crate::Printer;
use crate::Vec2;
use unicode_width::UnicodeWidthStr;
/// View used for debugging, showing logs.
pub struct DebugView {
// TODO: wrap log lines if needed, and save the line splits here.
}
impl DebugView {
/// Creates a new DebugVi... |
}
| {
// Uh?
} | identifier_body |
debug_view.rs | use crate::logger;
use crate::theme;
use crate::view::View;
use crate::Printer;
use crate::Vec2;
use unicode_width::UnicodeWidthStr;
/// View used for debugging, showing logs.
pub struct DebugView {
// TODO: wrap log lines if needed, and save the line splits here.
}
impl DebugView {
/// Creates a new DebugVi... | (&self, printer: &Printer) {
let logs = logger::LOGS.lock().unwrap();
// Only print the last logs, so skip what doesn't fit
let skipped = logs.len().saturating_sub(printer.size.y);
for (i, record) in logs.iter().skip(skipped).enumerate() {
// TODO: Apply style to message? (E... | draw | identifier_name |
poll.rs |
/// A macro.
#[macro_export]
macro_rules! try_poll {
($e:expr) => (match $e {
$crate::Poll::NotReady => return $crate::Poll::NotReady,
$crate::Poll::Ok(t) => Ok(t),
$crate::Poll::Err(e) => Err(e),
})
}
/// Possible return values from the `Future::poll` method.
#[derive(Copy, Clone, Deb... |
}
impl<T, E> From<Result<T, E>> for Poll<T, E> {
fn from(r: Result<T, E>) -> Poll<T, E> {
match r {
Ok(t) => Poll::Ok(t),
Err(t) => Poll::Err(t),
}
}
}
| {
match self {
Poll::Ok(t) => Ok(t),
Poll::Err(t) => Err(t),
Poll::NotReady => panic!("unwrapping a Poll that wasn't ready"),
}
} | identifier_body |
poll.rs | /// A macro.
#[macro_export]
macro_rules! try_poll {
($e:expr) => (match $e {
$crate::Poll::NotReady => return $crate::Poll::NotReady,
$crate::Poll::Ok(t) => Ok(t),
$crate::Poll::Err(e) => Err(e),
})
}
/// Possible return values from the `Future::poll` method.
#[derive(Copy, Clone, Debu... | Ok(T),
/// Indicates that the future has failed, and this error is what the future
/// failed with.
Err(E),
}
impl<T, E> Poll<T, E> {
/// Change the success type of this `Poll` value with the closure provided
pub fn map<F, U>(self, f: F) -> Poll<U, E>
where F: FnOnce(T) -> U
{
... | /// what the future completed with. | random_line_split |
poll.rs |
/// A macro.
#[macro_export]
macro_rules! try_poll {
($e:expr) => (match $e {
$crate::Poll::NotReady => return $crate::Poll::NotReady,
$crate::Poll::Ok(t) => Ok(t),
$crate::Poll::Err(e) => Err(e),
})
}
/// Possible return values from the `Future::poll` method.
#[derive(Copy, Clone, Deb... | <F, U>(self, f: F) -> Poll<U, E>
where F: FnOnce(T) -> U
{
match self {
Poll::NotReady => Poll::NotReady,
Poll::Ok(t) => Poll::Ok(f(t)),
Poll::Err(e) => Poll::Err(e),
}
}
/// Change the error type of this `Poll` value with the closure provided
... | map | identifier_name |
lcm.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
... |
#[test]
fn lcm_fail() {
apply_fn_to_unsigneds!(lcm_fail_helper);
}
#[test]
fn test_checked_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: Option<T>) {
assert_eq!(x.checked_lcm(y), out);
}
test::<u8>(0, 0, Some(0));
test::<u16>(0, 6, Some(0));
test::<u32>(6, 0, Some(0));
tes... | } | random_line_split |
lcm.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn | <T: PrimitiveUnsigned>(x: T, y: T, out: T) {
assert_eq!(x.lcm(y), out);
let mut x = x;
x.lcm_assign(y);
assert_eq!(x, out);
}
test::<u8>(0, 0, 0);
test::<u16>(0, 6, 0);
test::<u32>(6, 0, 0);
test::<u64>(1, 6, 6);
test::<u128>(6, 1, 6);
test::<usize>(8, 12, 24... | test | identifier_name |
lcm.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
... |
});
unsigned_gen::<T>().test_properties(|x| {
assert_eq!(x.checked_lcm(x), Some(x));
assert_eq!(x.checked_lcm(T::ONE), Some(x));
assert_eq!(x.checked_lcm(T::ZERO), Some(T::ZERO));
});
unsigned_triple_gen_var_19::<T>().test_properties(|(x, y, z)| {
if x!= T::ZERO && y!=... | {
assert_eq!(x.lcm(y), lcm);
} | conditional_block |
lcm.rs | use malachite_base::num::basic::unsigneds::PrimitiveUnsigned;
use malachite_base_test_util::generators::{
unsigned_gen, unsigned_pair_gen_var_33, unsigned_pair_gen_var_34, unsigned_triple_gen_var_19,
};
use std::panic::catch_unwind;
#[test]
fn test_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: T) {
... |
#[test]
fn test_checked_lcm() {
fn test<T: PrimitiveUnsigned>(x: T, y: T, out: Option<T>) {
assert_eq!(x.checked_lcm(y), out);
}
test::<u8>(0, 0, Some(0));
test::<u16>(0, 6, Some(0));
test::<u32>(6, 0, Some(0));
test::<u64>(1, 6, Some(6));
test::<u128>(6, 1, Some(6));
test::<us... | {
apply_fn_to_unsigneds!(lcm_fail_helper);
} | identifier_body |
args.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> &[OsString] {
self.iter.as_slice()
}
}
impl Iterator for Args {
type Item = OsString;
fn next(&mut self) -> Option<OsString> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl ExactSizeIterator for Args {
f... | inner_debug | identifier_name |
args.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | Args {
iter: v.into_iter(),
_dont_send_or_sync_me: PhantomData,
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn inner_debug(&self) -> &[OsString] {
self.iter.as_slice()
}
}
impl Iterator for Args {
... | pub unsafe fn cleanup() {
}
pub fn args() -> Args {
let v = ArgsSysCall::perform(); | random_line_split |
args.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub unsafe fn cleanup() {
}
pub fn args() -> Args {
let v = ArgsSysCall::perform();
Args {
iter: v.into_iter(),
_dont_send_or_sync_me: PhantomData,
}
}
pub struct Args {
iter: vec::IntoIter<OsString>,
_dont_send_or_sync_me: PhantomData<*mut ()>,
}
impl Args {
pub fn inner_de... | {
// On wasm these should always be null, so there's nothing for us to do here
} | identifier_body |
response.rs | use std::{fmt,str};
use std::collections::HashMap;
pub type Headers = HashMap<String, Vec<String>>;
pub struct Response {
code: uint,
hdrs: Headers,
body: Vec<u8>
}
impl Response {
pub fn new(code: uint, hdrs: Headers, body: Vec<u8>) -> Response {
Response {
code: code,
... |
}
impl fmt::Show for Response {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::FormatError> {
try!(write!(fmt, "Response {{{}, ", self.code));
for (name, val) in self.hdrs.iter() {
try!(write!(fmt, "{}: {}, ", name, val.connect(", ")));
}
match str::from_u... | {
self.body
} | identifier_body |
response.rs | use std::{fmt,str};
use std::collections::HashMap;
pub type Headers = HashMap<String, Vec<String>>;
pub struct Response {
code: uint,
hdrs: Headers,
body: Vec<u8>
}
impl Response {
pub fn new(code: uint, hdrs: Headers, body: Vec<u8>) -> Response {
Response {
code: code,
... | (&self) -> uint {
self.code
}
pub fn get_headers<'a>(&'a self) -> &'a Headers {
&self.hdrs
}
pub fn get_header<'a>(&'a self, name: &str) -> &'a [String] {
self.hdrs
.find_equiv(name)
.map(|v| v.as_slice())
.unwrap_or(&[])
}
pub fn get_b... | get_code | identifier_name |
response.rs | use std::{fmt,str};
use std::collections::HashMap;
pub type Headers = HashMap<String, Vec<String>>;
pub struct Response {
code: uint,
hdrs: Headers,
body: Vec<u8>
}
impl Response {
pub fn new(code: uint, hdrs: Headers, body: Vec<u8>) -> Response {
Response {
code: code,
... | Some(b) => try!(write!(fmt, "{}", b)),
None => try!(write!(fmt, "bytes[{}]", self.body.len()))
}
try!(write!(fmt, "]"));
Ok(())
}
} | random_line_split | |
aarch64_linux_android.rs | use crate::spec::{SanitizerSet, Target, TargetOptions};
// See https://developer.android.com/ndk/guides/abis.html#arm64-v8a
// for target ABI requirements.
pub fn target() -> Target {
Target {
llvm_target: "aarch64-linux-android".to_string(),
pointer_width: 64, | // As documented in https://developer.android.com/ndk/guides/cpu-features.html
// the neon (ASIMD) and FP must exist on all android aarch64 targets.
features: "+neon,+fp-armv8".to_string(),
supported_sanitizers: SanitizerSet::CFI | SanitizerSet::HWADDRESS,
..su... | data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
options: TargetOptions {
max_atomic_width: Some(128), | random_line_split |
aarch64_linux_android.rs | use crate::spec::{SanitizerSet, Target, TargetOptions};
// See https://developer.android.com/ndk/guides/abis.html#arm64-v8a
// for target ABI requirements.
pub fn target() -> Target | {
Target {
llvm_target: "aarch64-linux-android".to_string(),
pointer_width: 64,
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
options: TargetOptions {
max_atomic_width: Some(128),
// As doc... | identifier_body | |
aarch64_linux_android.rs | use crate::spec::{SanitizerSet, Target, TargetOptions};
// See https://developer.android.com/ndk/guides/abis.html#arm64-v8a
// for target ABI requirements.
pub fn | () -> Target {
Target {
llvm_target: "aarch64-linux-android".to_string(),
pointer_width: 64,
data_layout: "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
options: TargetOptions {
max_atomic_width: Some(128),
... | target | identifier_name |
count_is_at_least.rs | use malachite_base::iterators::count_is_at_least;
use std::iter::repeat; | assert_eq!(count_is_at_least(xs.iter(), n), result);
assert_eq!(count_is_at_least(xs.iter().rev(), n), result);
}
#[test]
fn test_count_is_at_least() {
count_is_at_least_helper(&[], 0, true);
count_is_at_least_helper(&[], 1, false);
count_is_at_least_helper(&[5], 0, true);
count_is_at_least_hel... |
fn count_is_at_least_helper(xs: &[u8], n: usize, result: bool) { | random_line_split |
count_is_at_least.rs | use malachite_base::iterators::count_is_at_least;
use std::iter::repeat;
fn count_is_at_least_helper(xs: &[u8], n: usize, result: bool) {
assert_eq!(count_is_at_least(xs.iter(), n), result);
assert_eq!(count_is_at_least(xs.iter().rev(), n), result);
}
#[test]
fn test_count_is_at_least() | {
count_is_at_least_helper(&[], 0, true);
count_is_at_least_helper(&[], 1, false);
count_is_at_least_helper(&[5], 0, true);
count_is_at_least_helper(&[5], 1, true);
count_is_at_least_helper(&[5], 2, false);
count_is_at_least_helper(&[1, 2, 3, 4], 4, true);
count_is_at_least_helper(&[1, 2, 3,... | identifier_body | |
count_is_at_least.rs | use malachite_base::iterators::count_is_at_least;
use std::iter::repeat;
fn | (xs: &[u8], n: usize, result: bool) {
assert_eq!(count_is_at_least(xs.iter(), n), result);
assert_eq!(count_is_at_least(xs.iter().rev(), n), result);
}
#[test]
fn test_count_is_at_least() {
count_is_at_least_helper(&[], 0, true);
count_is_at_least_helper(&[], 1, false);
count_is_at_least_helper(&[5... | count_is_at_least_helper | identifier_name |
main.rs | #![recursion_limit = "128"]
#![allow(dead_code)]
#[macro_use]
mod util;
mod dispatch;
use anyhow::Result;
use monger_core::os::OS_NAMES;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(about, author)]
enum Options {
/// clear the database files for an installed MongoDB version
Clear {
... | #[structopt(name = "MONGODB_ARGS", last(true))]
mongod_args: Vec<String>,
},
}
#[derive(Debug, StructOpt)]
enum Defaults {
/// clears the previously set default arguments
Clear,
/// prints the default arguments used when starting a mongod
Get,
/// sets the default arguments us... | id: String,
/// extra arguments for the mongod being run | random_line_split |
main.rs | #![recursion_limit = "128"]
#![allow(dead_code)]
#[macro_use]
mod util;
mod dispatch;
use anyhow::Result;
use monger_core::os::OS_NAMES;
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(about, author)]
enum | {
/// clear the database files for an installed MongoDB version
Clear {
/// the ID of the MongoDB version whose files should be cleared
#[structopt(name = "ID")]
id: String,
},
/// deletes an installed MongoDB version
Delete {
/// the ID of the MongoDB version to de... | Options | identifier_name |
main.rs | // tt - time tracker
//
// Usage: tt (stop the current task)
// tt <task name or description> start or resume a task
//
// Time tracking state is read from, and appended to./tt.txt
// There is no reporting functionality yet.
//
// Released under the GPL v3 licence.
extern crate chrono;
extern crate regex;
exter... | // but regain exclusive ownership after the scope is exited
// see: https://stackoverflow.com/questions/33831265/how-to-use-a-file-for-reading-and-writing
{
let reader = BufReader::new(&mut file); // "reader" is borrowing *the* mutable reference to file, for "reader"'s lifetime
for wrapped_... | {
let filename = "tt.txt";
// open a tt.txt file in the local directory
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(filename)
.unwrap();
// now read the whole file to get the latest state
... | identifier_body |
main.rs | // tt - time tracker
//
// Usage: tt (stop the current task)
// tt <task name or description> start or resume a task
//
// Time tracking state is read from, and appended to./tt.txt
// There is no reporting functionality yet.
//
// Released under the GPL v3 licence.
extern crate chrono;
extern crate regex;
exter... |
}
}
file.seek(End(0));
let now = Local::now();
if latest_date == None
|| latest_date.unwrap().year()!= now.year()
|| latest_date.unwrap().month()!= now.month()
|| latest_date.unwrap().day()!= now.day() {
// if today isn't the same date as the latest date found ... | {
let captures = time_activity_re.captures(&line).unwrap();
let hour = captures.at(1).unwrap().parse::<u32>().unwrap();
let minute = captures.at(2).unwrap().parse::<u32>().unwrap();
let activity = captures.at(3).unwrap();
latest_datetime =... | conditional_block |
main.rs | // tt - time tracker
//
// Usage: tt (stop the current task)
// tt <task name or description> start or resume a task
//
// Time tracking state is read from, and appended to./tt.txt
// There is no reporting functionality yet.
//
// Released under the GPL v3 licence.
extern crate chrono;
extern crate regex;
exter... | () {
let filename = "tt.txt";
// open a tt.txt file in the local directory
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(filename)
.unwrap();
// now read the whole file to get the latest state
... | main | identifier_name |
main.rs | // tt - time tracker
//
// Usage: tt (stop the current task)
// tt <task name or description> start or resume a task
//
// Time tracking state is read from, and appended to./tt.txt
// There is no reporting functionality yet.
//
// Released under the GPL v3 licence.
extern crate chrono;
extern crate regex;
exter... | // if there was no latest activity *and* there is no activity, then there's no point in writing a second blank line with just a time
if latest_activity == None {
return;
}
file.write_all(format!("{}\n", now.format("%H:%M")).as_bytes());
}
// "file" is automatically ... |
let activity = env::args().skip(1).join(" "); // use all arguments (apart from the program name) as a description of an activity
if (activity.len() > 0) {
file.write_all(format!("{} {}\n", now.format("%H:%M"), activity).as_bytes());
} else { | random_line_split |
tag-align-shape.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... | {
let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)};
let y = format!("{:?}", x);
println!("y = {:?}", y);
assert_eq!(y, "t_rec { c8: 22, t: a_tag_var(44) }".to_string());
} | identifier_body | |
tag-align-shape.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... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
#[derive(Debug)]
enum a_tag {
a_tag_var(u64)
}
#[derive(Debug)]
struct t_rec {
c8: u8,
t: a_tag
}
pub fn main() {
let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)};
let y = format!("{:?}", x);
... | random_line_split | |
tag-align-shape.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... | {
a_tag_var(u64)
}
#[derive(Debug)]
struct t_rec {
c8: u8,
t: a_tag
}
pub fn main() {
let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)};
let y = format!("{:?}", x);
println!("y = {:?}", y);
assert_eq!(y, "t_rec { c8: 22, t: a_tag_var(44) }".to_string());
}
| a_tag | identifier_name |
memorize.rs | use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;
use std::cell::RefCell;
use std::rc::Rc;
pub struct Memorizer<I, O> {
store: RefCell<HashMap<I, Rc<O>>>,
func: Box<Fn(&Memorizer<I, O>, &I) -> O>,
}
impl<I: Clone + Hash + Eq, O> Memorizer<I, O> {
pub fn | (f: Box<Fn(&Self, &I) -> O>) -> Memorizer<I, O> {
Memorizer {
store: RefCell::new(HashMap::new()),
func: f,
}
}
pub fn lookup(&self, i: I) -> Rc<O> {
if!self.store.borrow().contains_key(&i) {
let ref func = self.func;
let new_val = func(sel... | new | identifier_name |
memorize.rs | use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;
use std::cell::RefCell;
use std::rc::Rc;
pub struct Memorizer<I, O> {
store: RefCell<HashMap<I, Rc<O>>>,
func: Box<Fn(&Memorizer<I, O>, &I) -> O>,
}
impl<I: Clone + Hash + Eq, O> Memorizer<I, O> {
pub fn new(f: Box<Fn(&Self, &I) -> O>) ... | }
}
pub fn lookup(&self, i: I) -> Rc<O> {
if!self.store.borrow().contains_key(&i) {
let ref func = self.func;
let new_val = func(self, &i);
self.store.borrow_mut().insert(i.clone(), Rc::new(new_val));
}
self.store.borrow().get(&i).unwrap().clon... | Memorizer {
store: RefCell::new(HashMap::new()),
func: f, | random_line_split |
memorize.rs | use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;
use std::cell::RefCell;
use std::rc::Rc;
pub struct Memorizer<I, O> {
store: RefCell<HashMap<I, Rc<O>>>,
func: Box<Fn(&Memorizer<I, O>, &I) -> O>,
}
impl<I: Clone + Hash + Eq, O> Memorizer<I, O> {
pub fn new(f: Box<Fn(&Self, &I) -> O>) ... |
self.store.borrow().get(&i).unwrap().clone()
}
}
| {
let ref func = self.func;
let new_val = func(self, &i);
self.store.borrow_mut().insert(i.clone(), Rc::new(new_val));
} | conditional_block |
border.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Bor... | use app_units::Au;
use cssparser::ToCss;
use std::fmt;
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.0.to_css(dest)
}
}
#[inline]
pub fn parse(_context: &Parser... | ${helpers.predefined_type("border-%s-style" % side, "BorderStyle", "specified::BorderStyle::none", need_clone=True)}
% endfor
% for side in ["top", "right", "bottom", "left"]:
<%helpers:longhand name="border-${side}-width"> | random_line_split |
border.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Bor... | <W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
self.0.to_css(dest)
}
}
#[inline]
pub fn parse(_context: &ParserContext, input: &mut Parser)
-> Result<SpecifiedValue, ()> {
specified::parse_border_width(input).... | to_css | identifier_name |
border.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Bor... |
}
#[inline]
pub fn parse(_context: &ParserContext, input: &mut Parser)
-> Result<SpecifiedValue, ()> {
specified::parse_border_width(input).map(SpecifiedValue)
}
#[derive(Debug, Clone, PartialEq, HeapSizeOf)]
pub struct Specifi... | {
self.0.to_css(dest)
} | identifier_body |
stream.rs | // This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Represents a token stream.
use std::fmt;
use std::convert::Into;
use std::ops::Deref;
use engine::parser::token::{self, Token, Type};
use template;
use... |
pub fn iter(&'a self) -> Iter<'a> {
(&self.items).into_iter()
}
pub fn deref_iter(&'a self) -> DerefIter<'a> {
DerefIter { items: (&self.items).into_iter() }
}
}
impl<'a> fmt::Display for Stream<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let v... | {
&self.items
} | identifier_body |
stream.rs | // This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Represents a token stream.
use std::fmt;
use std::convert::Into;
use std::ops::Deref;
use engine::parser::token::{self, Token, Type};
use template;
use... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f,
" StreamDump{{ template: {template:?}, items: {items:?}}}",
template = self.template_str,
items = self.items_str)
}
}
// TODO: add another token_iter() to the main implementation [using.map(|i| i.into())... | fmt | identifier_name |
stream.rs | // This file is part of rust-web/twig
//
// For the copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//! Represents a token stream.
use std::fmt;
use std::convert::Into;
use std::ops::Deref;
use engine::parser::token::{self, Token, Type};
use template;
use... | Ok(&self)
} else {
traced_err!(TokenError::UnexpectedTokenAtItem {
reason: reason,
expected: <token::Pattern as Dump>::dump(&pattern),
found: self.dump(),
})
}
}
}
pub type ItemDump = Item; // may change as soon as ... | where T: token::Pattern + 'static
{
if pattern.matches(self.token()) { | random_line_split |
login.rs | use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CliResult, CargoResultExt, Config};
#[derive(Deserialize)]
pub struct Options {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: u... | let src = SourceId::crates_io(config)?;
let mut src = RegistrySource::remote(&src, config);
src.update()?;
let config = src.config()?.unwrap();
options.flag_host.clone().unwrap_or(config.api.unwrap())
}
... | {
config.configure(options.flag_verbose,
options.flag_quiet,
&options.flag_color,
options.flag_frozen,
options.flag_locked,
&options.flag_z)?;
if options.flag_registry.is_some() && !config.cli_unstable().un... | identifier_body |
login.rs | use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CliResult, CargoResultExt, Config};
#[derive(Deserialize)]
pub struct Options {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: u... |
pub const USAGE: &'static str = "
Save an api token from the registry locally. If token is not specified, it will be read from stdin.
Usage:
cargo login [options] [<token>]
Options:
-h, --help Print this message
--host HOST Host to set the token for
-v, --verbose... ... | #[serde(rename = "flag_Z")]
flag_z: Vec<String>,
flag_registry: Option<String>,
} | random_line_split |
login.rs | use std::io::prelude::*;
use std::io;
use cargo::ops;
use cargo::core::{SourceId, Source};
use cargo::sources::RegistrySource;
use cargo::util::{CargoError, CliResult, CargoResultExt, Config};
#[derive(Deserialize)]
pub struct | {
flag_host: Option<String>,
arg_token: Option<String>,
flag_verbose: u32,
flag_quiet: Option<bool>,
flag_color: Option<String>,
flag_frozen: bool,
flag_locked: bool,
#[serde(rename = "flag_Z")]
flag_z: Vec<String>,
flag_registry: Option<String>,
}
pub const USAGE: &'static str... | Options | identifier_name |
latest.rs | // Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | // except according to those terms.
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate tokio_core;
extern crate xkcd;
use hyper::Client;
use hyper_tls::HttpsConnector;
use tokio_core::reactor::Core;
fn main() {
let mut core = Core::new().unwrap();
let client = Client::configure()
... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
latest.rs | // Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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.o... | {
let mut core = Core::new().unwrap();
let client = Client::configure()
.connector(HttpsConnector::new(4, &core.handle()).unwrap())
.build(&core.handle());
// Retrieve the latest comic.
let work = xkcd::comics::latest(&client);
let latest_comic = core.run(work).unwrap();
println... | identifier_body | |
latest.rs | // Copyright (c) 2016-2017 Nikita Pekin and the xkcd_rs contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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.o... | () {
let mut core = Core::new().unwrap();
let client = Client::configure()
.connector(HttpsConnector::new(4, &core.handle()).unwrap())
.build(&core.handle());
// Retrieve the latest comic.
let work = xkcd::comics::latest(&client);
let latest_comic = core.run(work).unwrap();
printl... | main | identifier_name |
unused-async.rs | // edition:2018
// run-pass
#![allow(dead_code)]
#[must_use]
//~^ WARNING `must_use`
async fn test() -> i32 {
1
}
struct Wowee {}
impl Wowee {
#[must_use]
//~^ WARNING `must_use`
async fn test_method() -> i32 {
1
}
}
/* FIXME(guswynn) update this test when async-fn-in-traits works
trait... | #[must_use]
async fn test_other_trait() -> i32 {
WARNING must_use
1
}
}
*/
fn main() {
} | random_line_split | |
unused-async.rs | // edition:2018
// run-pass
#![allow(dead_code)]
#[must_use]
//~^ WARNING `must_use`
async fn test() -> i32 {
1
}
struct Wowee {}
impl Wowee {
#[must_use]
//~^ WARNING `must_use`
async fn test_method() -> i32 {
1
}
}
/* FIXME(guswynn) update this test when async-fn-in-traits works
trait... | {
} | identifier_body | |
unused-async.rs | // edition:2018
// run-pass
#![allow(dead_code)]
#[must_use]
//~^ WARNING `must_use`
async fn test() -> i32 {
1
}
struct | {}
impl Wowee {
#[must_use]
//~^ WARNING `must_use`
async fn test_method() -> i32 {
1
}
}
/* FIXME(guswynn) update this test when async-fn-in-traits works
trait Doer {
#[must_use]
async fn test_trait_method() -> i32;
WARNING must_use
async fn test_other_trait() -> i32;
}
impl... | Wowee | identifier_name |
filesearch.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... | <'a> {
pub sysroot: &'a Path,
pub addl_lib_search_paths: &'a RefCell<Vec<Path>>,
pub triple: &'a str,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path(&self, f: |&Path| -> FileMatch) {
let mut visited_dirs = HashSet::new();
let mut found = false;
debug!("filesearch: ... | FileSearch | identifier_name |
filesearch.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... |
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(... | {
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
} | identifier_body |
filesearch.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... | #[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
} | random_line_split | |
font_list.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::c_str_to_string;
use crate::text::util::is_cjk;
use fontconfig::fontconfig::{FcChar8, FcResultMatch, Fc... | else {
panic!();
};
let mut index: libc::c_int = 0;
let result =
FcPatternGetInteger(*font, FC_INDEX.as_ptr() as *mut c_char, 0, &mut index);
let index = if result == FcResultMatch {
index
} else {
... | {
c_str_to_string(file as *const c_char)
} | conditional_block |
font_list.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::c_str_to_string;
use crate::text::util::is_cjk;
use fontconfig::fontconfig::{FcChar8, FcResultMatch, FcSetSystem};
use fontconfig::fontconfig::{FcConfigGetCurrent, FcConfigGetFonts, FcConfigSubstitute};
use fontconfig::fontconfig::{FcDefaultSubstitute, FcFontMatch, FcNameParse, FcPatternGetString};
use fontc... | random_line_split | |
font_list.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::c_str_to_string;
use crate::text::util::is_cjk;
use fontconfig::fontconfig::{FcChar8, FcResultMatch, Fc... | {
let mut families = vec!["DejaVu Serif", "FreeSerif", "DejaVu Sans", "FreeSans"];
if let Some(codepoint) = codepoint {
if is_cjk(codepoint) {
families.push("TakaoPGothic");
families.push("Droid Sans Fallback");
families.push("WenQuanYi Micro Hei");
famil... | identifier_body | |
font_list.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::c_str_to_string;
use crate::text::util::is_cjk;
use fontconfig::fontconfig::{FcChar8, FcResultMatch, Fc... | <F>(family_name: &str, mut callback: F)
where
F: FnMut(String),
{
debug!("getting variations for {}", family_name);
unsafe {
let config = FcConfigGetCurrent();
let mut font_set = FcConfigGetFonts(config, FcSetSystem);
let font_set_array_ptr = &mut font_set;
let pattern = FcPa... | for_each_variation | identifier_name |
lib.rs | //! Carrier is an in-memory messaging system that exposes both C and Rust
//! interfaces with the goal of connecting two apps such that a) one app is
//! embedded inside of another (such as a rust app inside of a java app) or
//! b) two apps are embedded inside of a third and they need to communicate.
//!
//! Carrier u... |
/// Wipe out all queues
pub fn wipe() {
(*CONN).wipe();
}
#[cfg(test)]
mod tests {
use ::std::thread;
use super::*;
use ::std::sync::{Arc, RwLock};
#[test]
fn send_recv_simple() {
send("sendrecv", Vec::from(String::from("this is a test").as_bytes())).unwrap();
send_string("s... | {
(*CONN).count()
} | identifier_body |
lib.rs | //! Carrier is an in-memory messaging system that exposes both C and Rust
//! interfaces with the goal of connecting two apps such that a) one app is
//! embedded inside of another (such as a rust app inside of a java app) or
//! b) two apps are embedded inside of a third and they need to communicate.
//!
//! Carrier u... | (&self, val: i32) {
let mut mguard = self.messages.write().expect("Queue.inc_messages() -- failed to grab write lock");
(*mguard) += val;
}
/// Increment the number of users this queue has by a certain amount (1).
fn inc_users(&self, val: i32) {
let mut uguard = self.users.write().e... | inc_messages | identifier_name |
lib.rs | //! Carrier is an in-memory messaging system that exposes both C and Rust
//! interfaces with the goal of connecting two apps such that a) one app is
//! embedded inside of another (such as a rust app inside of a java app) or
//! b) two apps are embedded inside of a third and they need to communicate.
//!
//! Carrier u... | else {
let queue = Arc::new(Queue::new());
(*guard).insert(channel.clone(), queue.clone());
queue
}
}
fn exists(&self, channel: &String) -> bool {
let guard = self.queues.read().expect("Carrier.exists() -- failed to grab read lock");
(*guard).contain... | {
(*guard).get(channel).expect("Carrier.ensure() -- failed to grab map item").clone()
} | conditional_block |
lib.rs | //! Carrier is an in-memory messaging system that exposes both C and Rust
//! interfaces with the goal of connecting two apps such that a) one app is
//! embedded inside of another (such as a rust app inside of a java app) or
//! b) two apps are embedded inside of a third and they need to communicate.
//!
//! Carrier u... | fn send_recv_simple() {
send("sendrecv", Vec::from(String::from("this is a test").as_bytes())).unwrap();
send_string("sendrecv", String::from("this is another test")).unwrap();
let next = String::from_utf8(recv_nb("sendrecv").unwrap().unwrap()).unwrap();
assert_eq!(next, "this is a ... |
#[test] | random_line_split |
std_vec.rs | use std::cmp::Ordering;
impl<T> Collection for Vec<T> {
type Item = T;
}
impl<T> RetainsOrder for Vec<T> {}
impl<T> Sortable for Vec<T> {
fn sort<F>(&mut self, f: F)
where
F: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
self.sort_by(f);
}
}
impl<T, O> SearchableByOrder<O> for V... | use super::{Collection, RetainsOrder, SearchableByOrder, SortOrder, Sortable, SortedInsert}; | random_line_split | |
std_vec.rs | use super::{Collection, RetainsOrder, SearchableByOrder, SortOrder, Sortable, SortedInsert};
use std::cmp::Ordering;
impl<T> Collection for Vec<T> {
type Item = T;
}
impl<T> RetainsOrder for Vec<T> {}
impl<T> Sortable for Vec<T> {
fn sort<F>(&mut self, f: F)
where
F: FnMut(&Self::Item, &Self::Ite... | (&mut self, x: T) {
let i = match self.search(&x) {
Ok(i) => i,
Err(i) => i,
};
self.insert(i, x);
}
}
| insert | identifier_name |
std_vec.rs | use super::{Collection, RetainsOrder, SearchableByOrder, SortOrder, Sortable, SortedInsert};
use std::cmp::Ordering;
impl<T> Collection for Vec<T> {
type Item = T;
}
impl<T> RetainsOrder for Vec<T> {}
impl<T> Sortable for Vec<T> {
fn sort<F>(&mut self, f: F)
where
F: FnMut(&Self::Item, &Self::Ite... |
}
| {
let i = match self.search(&x) {
Ok(i) => i,
Err(i) => i,
};
self.insert(i, x);
} | identifier_body |
regex_query.rs | use crate::error::TantivyError;
use crate::query::{AutomatonWeight, Query, Weight};
use crate::schema::Field;
use crate::Searcher;
use std::clone::Clone;
use std::sync::Arc;
use tantivy_fst::Regex;
/// A Regex Query matches all of the documents
/// containing a specific term that matches
/// a regex pattern.
///
/// W... | ) -> crate::Result<Box<dyn Weight>> {
Ok(Box::new(self.specialized_weight()))
}
}
#[cfg(test)]
mod test {
use super::RegexQuery;
use crate::assert_nearly_equals;
use crate::collector::TopDocs;
use crate::schema::TEXT;
use crate::schema::{Field, Schema};
use crate::{Index, IndexR... | impl Query for RegexQuery {
fn weight(
&self,
_searcher: &Searcher,
_scoring_enabled: bool, | random_line_split |
regex_query.rs | use crate::error::TantivyError;
use crate::query::{AutomatonWeight, Query, Weight};
use crate::schema::Field;
use crate::Searcher;
use std::clone::Clone;
use std::sync::Arc;
use tantivy_fst::Regex;
/// A Regex Query matches all of the documents
/// containing a specific term that matches
/// a regex pattern.
///
/// W... | <T: Into<Arc<Regex>>>(regex: T, field: Field) -> Self {
RegexQuery {
regex: regex.into(),
field,
}
}
fn specialized_weight(&self) -> AutomatonWeight<Regex> {
AutomatonWeight::new(self.field, self.regex.clone())
}
}
impl Query for RegexQuery {
fn weight(
... | from_regex | identifier_name |
regex_query.rs | use crate::error::TantivyError;
use crate::query::{AutomatonWeight, Query, Weight};
use crate::schema::Field;
use crate::Searcher;
use std::clone::Clone;
use std::sync::Arc;
use tantivy_fst::Regex;
/// A Regex Query matches all of the documents
/// containing a specific term that matches
/// a regex pattern.
///
/// W... |
#[test]
pub fn test_regex_query() -> crate::Result<()> {
let (reader, field) = build_test_index()?;
let matching_one = RegexQuery::from_pattern("jap[ao]n", field)?;
let matching_zero = RegexQuery::from_pattern("jap[A-Z]n", field)?;
verify_regex_query(matching_one, matching_zer... | {
let searcher = reader.searcher();
{
let scored_docs = searcher
.search(&query_matching_one, &TopDocs::with_limit(2))
.unwrap();
assert_eq!(scored_docs.len(), 1, "Expected only 1 document");
let (score, _) = scored_docs[0];
... | identifier_body |
day22.rs | #[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone,Debug)]
struct GameState {
player : Character,
boss : Character,
... | active_spells : Vec<Spell>
}
impl Character {
fn new(hp : i32, damage : u32, mana : u32) -> Character {
Character {
hp : hp,
damage : damage,
armor : 0,
mana : mana,
mana_usage : 0,
active_spells : Vec::new()
}
}
}
#... | armor : u32,
mana : u32,
mana_usage : u32, | random_line_split |
day22.rs | #[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone,Debug)]
struct GameState {
player : Character,
boss : Character,
... | (&mut self) {
if!self.players_turn {
let damage = std::cmp::max(1, self.boss.damage - self.player.armor);
self.player.hp -= damage as i32;
}
}
fn apply_spells(&mut self) {
self.player.armor = 0; // Init to no shield
for s in &mut self.player.active_spell... | apply_boss_damage | identifier_name |
day22.rs | #[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone,Debug)]
struct GameState {
player : Character,
boss : Character,
... |
}
mana_usage
}
fn build_spell_list() -> Vec<Spell> {
let mut spells = Vec::new();
spells.push(Spell::new("Shield", 113, 0, 0, 7, 0, 6));
spells.push(Spell::new("Poison", 173, 3, 0, 0, 0, 6));
spells.push(Spell::new("Magic Missle", 53, 4, 0, 0, 0, 0));
spells.push(Spell:... | {
// Run boss code
game.apply_boss_damage();
if game.player.hp > 0 {
game.players_turn = true;
// If neither player or boss won, start next round
let new_mana_usage = find_min_mana_usage(game.clone(), spells, hard_mode);
... | conditional_block |
day22.rs | #[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use regex::Regex;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone,Debug)]
struct GameState {
player : Character,
boss : Character,
... |
fn add_spell(&mut self, spell : Spell) {
self.player.mana -= spell.mana_cost;
self.player.mana_usage += spell.mana_cost;
if spell.turns > 0 {
if spell.name == "Shield" || spell.name == "Recharge" {
self.player.active_spells.push(spell);
} else {
... | {
let mut on = false;
for s in &self.player.active_spells {
if s.name == spell.name {
on = true;
break;
}
}
if !on {
for s in &self.boss.active_spells {
if s.name == spell.name {
on =... | identifier_body |
htmlfontelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::bindings::codegen::Bin... | {
RelativePlus,
RelativeMinus,
Absolute,
}
let mut input_chars = input.chars().peekable();
let parse_mode = match input_chars.peek() {
// Step 4
None => return AttrValue::String(original_input.into()),
// Step 5
Some(&'+') => {
let _ = in... | ParseMode | identifier_name |
htmlfontelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::bindings::codegen::Bin... | ParseMode::RelativePlus
}
Some(&'-') => {
let _ = input_chars.next(); // consume the '-'
ParseMode::RelativeMinus
}
Some(_) => ParseMode::Absolute,
};
// Steps 6, 7, 8
let mut value = match read_numbers(input_chars) {
(Some(v), _)... | {
let original_input = input;
// Steps 1 & 2 are not relevant
// Step 3
input = input.trim_matches(HTML_SPACE_CHARACTERS);
enum ParseMode {
RelativePlus,
RelativeMinus,
Absolute,
}
let mut input_chars = input.chars().peekable();
let parse_mode = match input_char... | identifier_body |
htmlfontelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLFontElementBinding;
use dom::bindings::codegen::Bin... | use dom::node::Node;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever_atoms::LocalName;
use servo_atoms::Atom;
use style::attr::AttrValue;
use style::str::{HTML_SPACE_CHARACTERS, read_numbers};
#[dom_struct]
pub struct HTMLFontElement {
htmlelement: HTMLElement,
}
impl HTMLFontE... | use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{Element, RawLayoutElementHelpers};
use dom::htmlelement::HTMLElement; | random_line_split |
ty.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 ... |
fn mk_lifetime(cx: @ExtCtxt, span: span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn to_ty(&self,
cx: @ExtCtxt,
span: span,
... | {
Tuple(~[])
} | identifier_body |
ty.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 ... | Tuple(~[])
}
fn mk_lifetime(cx: @ExtCtxt, span: span, lt: &Option<&str>) -> Option<ast::Lifetime> {
match *lt {
Some(ref s) => Some(cx.lifetime(span, cx.ident_of(*s))),
None => None
}
}
impl<'self> Ty<'self> {
pub fn to_ty(&self,
cx: @ExtCtxt,
span: sp... | pub fn nil_ty() -> Ty<'static> { | random_line_split |
ty.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 ... | (&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Ty {
match *self {
Ptr(ref ty, ref ptr) => {
let raw_ty = ty.to_ty(cx, span, self_ty, self_generics);
... | to_ty | identifier_name |
ty.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 to_path(&self,
cx: @ExtCtxt,
span: span,
self_ty: ident,
self_generics: &Generics)
-> ast::Path {
match *self {
Self => {
let self_params = do self_generics.ty_... | {
let ty = if fields.is_empty() {
ast::ty_nil
} else {
ast::ty_tup(fields.map(|f| f.to_ty(cx, span, self_ty, self_generics)))
};
cx.ty(span, ty)
} | conditional_block |
io.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... |
if right.len() > 0 {
self.buf.push_all(right);
}
}
// Bump us forward
self.pos += buf.len();
Ok(())
}
}
impl Seek for SeekableMemWriter {
#[inline]
fn tell(&self) -> IoResult<u64> { Ok(self.pos as u64) }
#[inline]
fn seek(&m... | {
slice::bytes::copy_memory(self.buf.slice_from_mut(self.pos), left);
} | conditional_block |
io.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... | (n: uint) -> SeekableMemWriter {
SeekableMemWriter { buf: Vec::with_capacity(n), pos: 0 }
}
/// Acquires an immutable reference to the underlying buffer of this
/// `SeekableMemWriter`.
///
/// No method is exposed for acquiring a mutable reference to the buffer
/// because it could cor... | with_capacity | identifier_name |
io.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!(writer.get_ref(), b);
writer.seek(-1, io::SeekEnd).unwrap();
writer.write(&[1, 2]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
assert_eq!(writer.get_ref(), b);
writer.seek(1, io::SeekEnd).unwrap();
writer.write(&[1]).unwrap();
let b:... | {
let mut writer = SeekableMemWriter::new();
assert_eq!(writer.tell(), Ok(0));
writer.write(&[0]).unwrap();
assert_eq!(writer.tell(), Ok(1));
writer.write(&[1, 2, 3]).unwrap();
writer.write(&[4, 5, 6, 7]).unwrap();
assert_eq!(writer.tell(), Ok(8));
let b: ... | identifier_body |
io.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... | let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 7];
assert_eq!(writer.get_ref(), b);
writer.seek(-1, io::SeekEnd).unwrap();
writer.write(&[1, 2]).unwrap();
let b: &[_] = &[3, 4, 2, 0, 1, 5, 6, 1, 2];
assert_eq!(writer.get_ref(), b);
writer.seek(1, io::SeekEnd).unwrap();
... | writer.seek(1, io::SeekCur).unwrap();
writer.write(&[0, 1]).unwrap(); | random_line_split |
main.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... |
if let Err(err) = server::run(args) {
println!("{}", err);
process::exit(1);
}
}
| {
core::output::set_no_color(true);
} | conditional_block |
main.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | //
// This does, of course, rely on the option name used here staying
// in sync with the name used in the Supervisor.
//
// There is currently no short option to check; just the long
// name.
if args.contains(&String::from("--no-color")) {
core::output::set_no_color(true);
}
... | // `--no-color` and set our global variable accordingly. | random_line_split |
main.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | process::exit(1);
}
}
| {
env_logger::init();
let args: Vec<String> = env::args().skip(1).collect();
// Since we have access to all the arguments passed to the
// Supervisor here, we can simply see if the user requested
// `--no-color` and set our global variable accordingly.
//
// This does, of course, rely on t... | identifier_body |
main.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless r... | () {
env_logger::init();
let args: Vec<String> = env::args().skip(1).collect();
// Since we have access to all the arguments passed to the
// Supervisor here, we can simply see if the user requested
// `--no-color` and set our global variable accordingly.
//
// This does, of course, rely o... | main | identifier_name |
middleware.rs | //! Traits to implement middleware types.
//!
//! This module defined the middleware traits for the closures that would be used as handlers and
//! middlewares in the application. This provides nice compile time guarantees of the what each
//! specific middleware can do and return. If anything else is returned then it ... | <'m, 'r>(&'m self, req: &Request<'m, 'r>) {
(*self)(req);
}
}
/// The actual logic for handling the request and writing the response is a part of this
/// middleware.
///
/// Here you have access to both the request and response objects and you need to write the
/// response for a particular request in the... | execute | identifier_name |
middleware.rs | //! Traits to implement middleware types.
//!
//! This module defined the middleware traits for the closures that would be used as handlers and
//! middlewares in the application. This provides nice compile time guarantees of the what each
//! specific middleware can do and return. If anything else is returned then it ... |
}
/// Any logic to be executed per request after the response has been sent is a part of this
/// middleware.
///
/// This has access to the `Request` and `ShadowResponse` objects.
///
/// Typical uses for this middleware could be in logging something after the request is served.
pub trait AfterMiddleware: Send + Syn... | {
(*self)(req, res)
} | identifier_body |
middleware.rs | //! Traits to implement middleware types.
//!
//! This module defined the middleware traits for the closures that would be used as handlers and
//! middlewares in the application. This provides nice compile time guarantees of the what each
//! specific middleware can do and return. If anything else is returned then it ... | /// write a response from a `BeforeMiddleware`. You need to implement a `Handler` to do that.
///
/// Typical uses for this middleware is for checking certain header or some form of authentication
/// on the request before it is served by the application.
pub trait BeforeMiddleware: Send + Sync +'static {
fn execut... | /// Implements the kind of middleware that is executed when a request has arrived but before it is
/// passed on to the handler for being processed.
///
/// You have access to the request here and can do some pre-processing as required, but you cannot | random_line_split |
action_plugin.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::{
action_plugins::{
check_kernel, check_stonith, firewall_cmd, high_availability, kernel_module, lamigo, ldev,
lpurge, ltuer, lustre,
... | () -> action_plugins::Actions {
let map = action_plugins::Actions::default()
.add_plugin("start_unit", iml_systemd::start_unit)
.add_plugin("stop_unit", iml_systemd::stop_unit)
.add_plugin("enable_unit", iml_systemd::enable_unit)
.add_plugin("disable_unit", iml_systemd::disable_unit)
... | create_registry | identifier_name |
action_plugin.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. | action_plugins::{
check_kernel, check_stonith, firewall_cmd, high_availability, kernel_module, lamigo, ldev,
lpurge, ltuer, lustre,
ntp::{action_configure, is_ntp_configured},
ostpool, package, postoffice,
stratagem::{
action_cloudsync, action_filesync, action_mir... |
use crate::{ | random_line_split |
action_plugin.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::{
action_plugins::{
check_kernel, check_stonith, firewall_cmd, high_availability, kernel_module, lamigo, ldev,
lpurge, ltuer, lustre,
... | )
.add_plugin("mount", lustre::client::mount)
.add_plugin("mount_many", lustre::client::mount_many)
.add_plugin("unmount", lustre::client::unmount)
.add_plugin("unmount_many", lustre::client::unmount_many)
.add_plugin("ha_resource_start", high_availability::start_resource)
... | {
let map = action_plugins::Actions::default()
.add_plugin("start_unit", iml_systemd::start_unit)
.add_plugin("stop_unit", iml_systemd::stop_unit)
.add_plugin("enable_unit", iml_systemd::enable_unit)
.add_plugin("disable_unit", iml_systemd::disable_unit)
.add_plugin("restart_... | identifier_body |
fat.rs | use alloc::vec::Vec;
use core::mem;
use crate::address::Align;
#[repr(packed)]
pub struct BPB {
jmp_instr: [u8; 3],
oem_identifier: [u8; 8],
bytes_per_sector: u16,
sectors_per_cluster: u8,
resd_sectors: u16,
fat_count: u8,
root_dir_entry_count: u16,
sector_count: u16, // if... | {
Free,
Used,
Bad,
Reserved,
End,
Invalid,
}
pub enum FatFormat {
Fat12,
Fat16,
Fat32,
}
impl FatFormat {
pub fn cluster_type(&self, cluster: u32) -> ClusterType {
match self {
Self::Fat12 => match cluster {
0 => ClusterTy... | ClusterType | identifier_name |
fat.rs | use alloc::vec::Vec;
use core::mem;
use crate::address::Align;
#[repr(packed)]
pub struct BPB {
jmp_instr: [u8; 3],
oem_identifier: [u8; 8],
bytes_per_sector: u16,
sectors_per_cluster: u8,
resd_sectors: u16,
fat_count: u8,
root_dir_entry_count: u16,
sector_count: u16, // if... |
} else {
None
}
}
}
#[repr(packed)]
pub struct FatBPB {
bpb: BPB,
drive_number: u8,
win_nt_flags: u8,
signature: u8, // either 0x28 or 0x29
volume_id: u32,
volume_label: [u8; 11],
system_id: [u8; 8],
boot_code: [u8; 448],
partit... | {
Some((basename, Some(extension), oversized))
} | conditional_block |
fat.rs | use alloc::vec::Vec;
use core::mem;
use crate::address::Align;
#[repr(packed)]
pub struct BPB {
jmp_instr: [u8; 3],
oem_identifier: [u8; 8],
bytes_per_sector: u16,
sectors_per_cluster: u8,
resd_sectors: u16,
fat_count: u8,
root_dir_entry_count: u16,
sector_count: u16, // if... | }
if extension == [b' ', b' ', b' '] {
Some((basename, None, oversized))
} else {
Some((basename, Some(extension), oversized))
}
} else {
None
}
}
}
#[repr(packed)]
pub struct FatBPB {
bp... | basename[base_i] = c;
base_i += 1;
| random_line_split |
fat.rs | use alloc::vec::Vec;
use core::mem;
use crate::address::Align;
#[repr(packed)]
pub struct BPB {
jmp_instr: [u8; 3],
oem_identifier: [u8; 8],
bytes_per_sector: u16,
sectors_per_cluster: u8,
resd_sectors: u16,
fat_count: u8,
root_dir_entry_count: u16,
sector_count: u16, // if... | } else if Self::is_replace_char(*c) {
b'_'
} else {
*c
}
})
.filter(|c| Self::is_legal_dos_char(*c));
let mut ext_i = 0;
... | {
let mut parts = filename
.rsplitn(2, |c| *c == b'.');
if let Some(name) = parts.next() {
let mut basename = [b' '; 8];
let mut extension = [b' '; 3];
let mut oversized = false;
let base = if let Some(b) = parts.next() {
... | identifier_body |
map.rs | use std::cmp;
use rand::{self, Rng};
use tcod::bsp::{Bsp, TraverseOrder};
use consts;
use object::{self, actor, Object, ObjectClass};
use object::load::ObjectRandomizer;
use object::item::Function;
use ai::Ai;
pub const MAP_WIDTH: i32 = 80;
pub const MAP_HEIGHT: i32 = 43;
pub const FLOOR_WIDTH: i32 = 30;
pub const... |
}
}
let (stairs_x, stairs_y) = stairs;
let mut stairs_up = items.get_class("stairs up").create_object();
stairs_up.set_pos(stairs_x, stairs_y);
map[stairs_x as usize][stairs_y as usize].items.push(stairs_up);
}
for _ in 0..rand::thread_rng().gen_range(1,3) {... | {
let stairs_x = room.x1 + ((room.x2 - room.x1)/2);
let stairs_y = room.y1 + ((room.y2 - room.y1)/2);
stairs = (stairs_x, stairs_y);
} | conditional_block |
map.rs | use std::cmp;
use rand::{self, Rng};
use tcod::bsp::{Bsp, TraverseOrder};
use consts;
use object::{self, actor, Object, ObjectClass};
use object::load::ObjectRandomizer;
use object::item::Function;
use ai::Ai;
pub const MAP_WIDTH: i32 = 80;
pub const MAP_HEIGHT: i32 = 43;
pub const FLOOR_WIDTH: i32 = 30;
pub const... | if blocks == object::Blocks::Full {
return blocks
}
}
blocks
}
pub type Map = Vec<Vec<Tile>>;
#[derive(Clone, Copy, Debug)]
struct Rect {
x1: i32,
y1: i32,
x2: i32,
y2: i32,
}
impl Rect {
pub fn new(x: i32, y: i32, w: i32, h: i32)
-> Self {
Re... | {
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all actors in the map location to see if they block
// If only one thing blocks fully we know nothing can see through that
// tile, so we are don... | identifier_body |
map.rs | use std::cmp;
use rand::{self, Rng};
use tcod::bsp::{Bsp, TraverseOrder};
use consts;
use object::{self, actor, Object, ObjectClass};
use object::load::ObjectRandomizer;
use object::item::Function;
use ai::Ai;
pub const MAP_WIDTH: i32 = 80;
pub const MAP_HEIGHT: i32 = 43;
pub const FLOOR_WIDTH: i32 = 30;
pub const... | actors[consts::PLAYER].set_pos(1, room.y2 / 2);
}
}
for _ in 0..rand::thread_rng().gen_range(1,2) {
let room = rooms[rand::thread_rng().gen_range(0, rooms.len())];
let x = rand::thread_rng().gen_range(room.x1+1, room.x2);
let y = rand::thread_rng().gen_range(room.y1+... | actor_types: &object::load::ObjectTypes,
actors: &mut Vec<Object>) {
for room in rooms {
if room.x1 == 1 && room.y1 == 1 { | random_line_split |
map.rs | use std::cmp;
use rand::{self, Rng};
use tcod::bsp::{Bsp, TraverseOrder};
use consts;
use object::{self, actor, Object, ObjectClass};
use object::load::ObjectRandomizer;
use object::item::Function;
use ai::Ai;
pub const MAP_WIDTH: i32 = 80;
pub const MAP_HEIGHT: i32 = 43;
pub const FLOOR_WIDTH: i32 = 30;
pub const... | (x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks {
// Because actors are stored in a separate place from the map, we need
// to check both for actors marked as being in a place on the map,
// as well as all objects in the map location to see if they block
// If only one thing blocks ful... | is_blocked | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.