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
iso_8859_9.rs
pub fn charmap() -> [&'static str,.. 256]{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x...
"\xcb", // 0xcb "\xcc", // 0xcc "\xcd", // 0xcd "\xce", // 0xce "\xcf", // 0xcf "\u011e", // 0xd0 "\xd1", // 0xd1 "\xd2", // 0xd2 "\xd3", // 0xd3 "\xd4", // 0xd4 "\xd5", // 0xd5 "\xd6", // 0xd6 "\xd7", // 0xd7 "\xd8", // 0xd8 "\xd9", // 0xd9 "\xda", // 0xda "\xdb", // 0xdb "\xdc", // 0xdc "\u0130", // 0xdd "\u015e", //...
"\xc7", // 0xc7 "\xc8", // 0xc8 "\xc9", // 0xc9 "\xca", // 0xca
random_line_split
iso_8859_9.rs
pub fn
() -> [&'static str,.. 256]{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 "...
charmap
identifier_name
iso_8859_9.rs
pub fn charmap() -> [&'static str,.. 256]
"\x14", // 0x14 "\x15", // 0x15 "\x16", // 0x16 "\x17", // 0x17 "\x18", // 0x18 "\x19", // 0x19 "\x1a", // 0x1a "\x1b", // 0x1b "\x1c", // 0x1c "\x1d", // 0x1d "\x1e", // 0x1e "\x1f", // 0x1f " ", // 0x20 "!", // 0x21 "\"", // 0x22 "#", // 0x23 "$", // 0x24 "%", // 0x25 "&", // 0x26 "'", // 0x27 "(", // 0x28 ")", // 0x...
{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 "\x13", // 0x13
identifier_body
macro_parser.rs
[a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat...
count_names(&delim.tts) } &TtToken(_, MatchNt(..)) => { 1 } &TtToken(_, _) => 0, } }) } pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos) -> Box<MatcherPos> { let...
} &TtDelimited(_, ref delim) => {
random_line_split
macro_parser.rs
a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (...
> TokenTree { match self { &TtSeq(ref v) => v[index].clone(), &Tt(ref tt) => tt.get_tt(index), } } } /// an unzipping of `TokenTree`s #[derive(Clone)] struct MatcherTtFrame { elts: TokenTreeOrTokenTreeVec, idx: usize, } #[derive(Clone)] pub struct MatcherPos { s...
ize) -
identifier_name
macro_parser.rs
a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (...
Token(sp, SubstNt(..)) => { return Error(sp, "Cannot transcribe in macro LHS".to_string()) } seq @ TtDelimited(..) | seq @ TtToken(_, DocComment(..)) => { let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq)); ...
// Built-in nonterminals never start with these tokens, // so we can eliminate them from consideration. match tok { token::CloseDelim(_) => {}, _ => bb_eis.push(ei), } }...
conditional_block
macro_crate_test.rs
// Copyright 2013-2015 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...
} } pub fn foo() {}
{ let mut new_it = (*tt).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::TraitItem(P(new_it))); }
conditional_block
macro_crate_test.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: Annotatable) -> Annotatable { match it { Annotatable::Item(it) => { Annotatable::Item(P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, ...
expand_into_foo_multi
identifier_name
macro_crate_test.rs
// Copyright 2013-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
cx.span_fatal(sp, "make_a_1 takes no arguments"); } MacEager::expr(quote_expr!(cx, 1)) } // See Issue #15750 fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { // Parse an expression and emit it unchanged. let mut parser = parse::...
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { if !tts.is_empty() {
random_line_split
macro_crate_test.rs
// Copyright 2013-2015 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 expand_into_foo_multi(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: Annotatable) -> Annotatable { match it { Annotatable::Item(it) => { Annotatable::Item(P(Item { attrs: it.attrs.clone(), ...
{ P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() }) }
identifier_body
mod.rs
mod sender; mod bus; use std::error; use std::fmt; use std::collections::HashMap; pub use self::sender::Reader; #[derive(Debug)] pub enum BusError { NoSuchChannel(String), } impl fmt::Display for BusError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { BusError::...
} } } impl error::Error for BusError { fn description(&self) -> &str { match *self { BusError::NoSuchChannel(_) => "No such channel", } } } pub struct BusSystem { busses: HashMap<String, bus::Bus<f64>>, } impl BusSystem { // ok, there's a big fat leak : when th...
{ fmt.debug_struct("NoSuchChannel") .field("channel", &chan) .finish() }
conditional_block
mod.rs
mod sender; mod bus; use std::error; use std::fmt; use std::collections::HashMap; pub use self::sender::Reader; #[derive(Debug)] pub enum BusError { NoSuchChannel(String), } impl fmt::Display for BusError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { BusError::...
{ a: Reader<f64>, b: Reader<f64>, } impl Stuff { fn doit(&self) -> f64 { self.a.value() + self.b.value() } } #[test] fn test_bus_system() { let mut bus = BusSystem::new(); let stuff = Stuff { a: bus.sub("a"), b:...
Stuff
identifier_name
mod.rs
mod sender; mod bus; use std::error; use std::fmt; use std::collections::HashMap; pub use self::sender::Reader; #[derive(Debug)] pub enum BusError { NoSuchChannel(String), } impl fmt::Display for BusError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { BusError::...
pub fn publish(&mut self, chan: &str, value: f64) -> Result<(), BusError> { self.busses.get_mut(chan).map(|c| c.publish(value)).ok_or( BusError::NoSuchChannel(chan.to_string()), ) } } #[cfg(test)] mod tests { use super::*; struct Stuff { a: Reader<f64>, b...
{ self.busses .entry(chan.to_string()) .or_insert(bus::Bus::new(0.0)) .subscribe() }
identifier_body
mod.rs
mod sender; mod bus; use std::error; use std::fmt; use std::collections::HashMap; pub use self::sender::Reader; #[derive(Debug)] pub enum BusError { NoSuchChannel(String), } impl fmt::Display for BusError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { BusError::...
pub struct BusSystem { busses: HashMap<String, bus::Bus<f64>>, } impl BusSystem { // ok, there's a big fat leak : when there are no listenner to a bus, it stays in the map. pub fn new() -> BusSystem { BusSystem { busses: HashMap::new() } } // ideally sub<T> -> Receiver<T> pub fn sub(&m...
}
random_line_split
lib.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 std::{collections::BTreeSet, env}; pub mod api; pub mod api_utils; pub mod display_utils; pub mod error; pub mod filesystem; pub mod nginx; pub mod ostpool; pub mo...
pub fn selfname(suffix: Option<&str>) -> Option<String> { match env::var("CLI_NAME") { Ok(n) => suffix.map(|s| format!("{}-{}", n, s)).or_else(|| Some(n)), Err(_) => exe_name(), } }
{ Some( std::env::current_exe() .ok()? .file_stem()? .to_str()? .to_string(), ) }
identifier_body
lib.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 std::{collections::BTreeSet, env}; pub mod api; pub mod api_utils; pub mod display_utils; pub mod error; pub mod filesystem; pub mod nginx; pub mod ostpool; pub mo...
} }
pub fn selfname(suffix: Option<&str>) -> Option<String> { match env::var("CLI_NAME") { Ok(n) => suffix.map(|s| format!("{}-{}", n, s)).or_else(|| Some(n)), Err(_) => exe_name(),
random_line_split
lib.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 std::{collections::BTreeSet, env}; pub mod api; pub mod api_utils; pub mod display_utils; pub mod error; pub mod filesystem; pub mod nginx; pub mod ostpool; pub mo...
(hosts: &[String]) -> Result<BTreeSet<String>, error::ImlManagerCliError> { let parsed: Vec<BTreeSet<String>> = hosts .iter() .map(|x| hostlist_parser::parse(x)) .collect::<Result<_, _>>()?; let union = parsed .into_iter() .fold(BTreeSet::new(), |acc, h| acc.union(&h).cloned(...
parse_hosts
identifier_name
associated-types-no-suitable-supertrait.rs
// Check that we get an error when you use `<Self as Get>::Value` in // the trait definition but `Self` does not, in fact, implement `Get`. // // See also associated-types-no-suitable-supertrait-2.rs, which checks // that we see the same error if we get around to checking the default // method body. // // See also run-...
<U:Get>(&self, foo: U, bar: <Self as Get>::Value) {} //~^ ERROR the trait bound `Self: Get` is not satisfied } impl<T:Get> Other for T { fn uhoh<U:Get>(&self, foo: U, bar: <(T, U) as Get>::Value) {} //~^ ERROR the trait bound `(T, U): Get` is not satisfied } fn main() { }
uhoh
identifier_name
associated-types-no-suitable-supertrait.rs
// Check that we get an error when you use `<Self as Get>::Value` in // the trait definition but `Self` does not, in fact, implement `Get`. // // See also associated-types-no-suitable-supertrait-2.rs, which checks // that we see the same error if we get around to checking the default // method body. // // See also run-...
//~^ ERROR the trait bound `(T, U): Get` is not satisfied } fn main() { }
{}
identifier_body
associated-types-no-suitable-supertrait.rs
// Check that we get an error when you use `<Self as Get>::Value` in // the trait definition but `Self` does not, in fact, implement `Get`. // // See also associated-types-no-suitable-supertrait-2.rs, which checks // that we see the same error if we get around to checking the default // method body.
trait Get { type Value; } trait Other { fn uhoh<U:Get>(&self, foo: U, bar: <Self as Get>::Value) {} //~^ ERROR the trait bound `Self: Get` is not satisfied } impl<T:Get> Other for T { fn uhoh<U:Get>(&self, foo: U, bar: <(T, U) as Get>::Value) {} //~^ ERROR the trait bound `(T, U): Get` is not sati...
// // See also run-pass/associated-types-projection-to-unrelated-trait.rs, // which checks that the trait interface itself is not considered an // error as long as all impls satisfy the constraint.
random_line_split
main.rs
/* License stuff ---------------------------------------------------------- Copyright 2013 Joris Rehm Licensed under the Apache License, Version 2.0. Licensed under The MIT License. See joined files "LICENSE-APACHE" and "LICENSE-MIT". ---------------------------------------------------------- */ ...
'event : loop { match sdl::event::poll_event() { sdl::event::QuitEvent => break'main, sdl::event::NoEvent => break 'event, sdl::event::KeyEvent(k, _, _, _) if k == sdl::event::EscapeKey => break'main, ...
'main : loop {
random_line_split
main.rs
/* License stuff ---------------------------------------------------------- Copyright 2013 Joris Rehm Licensed under the Apache License, Version 2.0. Licensed under The MIT License. See joined files "LICENSE-APACHE" and "LICENSE-MIT". ---------------------------------------------------------- */ ...
/* ----------------------------------------------------------- */ // TODO define an integration function and refactor // compute_velocity and compute_position. // TODO it's not really usefull to record acceleration /* ----------------------------------------------------------- */ fn init_system() -> ~Manager...
{ let mut mng = Manager::new(); let e1 = mng.new_entity(); assert!( e1 == 0 ); let e2 = mng.new_entity(); assert!( e2 == 1 ); }
identifier_body
main.rs
/* License stuff ---------------------------------------------------------- Copyright 2013 Joris Rehm Licensed under the Apache License, Version 2.0. Licensed under The MIT License. See joined files "LICENSE-APACHE" and "LICENSE-MIT". ---------------------------------------------------------- */ ...
() -> ~Manager { println("use RUST_LOG=3 to see log"); let mut mng = Manager::new(); let zero = Vec(0., 0., 0.); // for i in range(0,10) { let entity2 = mng.new_entity(); mng.table_position.set(entity2, Vec::rand_around_origin(5., 25.) ); mng.table_velocity.set(entity2, Vec::rand_around_origin(0.2...
init_system
identifier_name
lib.rs
// ================================================================= // // * WARNING * // // This file is generated! // // Changes made to this file will be overwritten. If changes are // required to the generated code, the service_crategen project // must be updated to g...
extern crate serde_derive; extern crate serde_json; mod generated; mod custom; pub use generated::*; pub use custom::*;
random_line_split
disallow_id_as_alias.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::WithLocation; use errors::try2; use graphql_ir::{ LinkedField, Program, ScalarField, ValidationError, ValidationMes...
} } } impl<'s> Validator for DisallowIdAsAlias<'s> { const NAME: &'static str = "DisallowIdAsAlias"; const VALIDATE_ARGUMENTS: bool = false; const VALIDATE_DIRECTIVES: bool = false; fn validate_linked_field(&mut self, field: &LinkedField) -> Result<(), Vec<ValidationError>> { if le...
Self { program, id_key: "id".intern(),
random_line_split
disallow_id_as_alias.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::WithLocation; use errors::try2; use graphql_ir::{ LinkedField, Program, ScalarField, ValidationError, ValidationMes...
else { Ok(()) } }
{ Err(vec![ValidationError::new( ValidationMessage::DisallowIdAsAliasError(), vec![alias.location], )]) }
conditional_block
disallow_id_as_alias.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::WithLocation; use errors::try2; use graphql_ir::{ LinkedField, Program, ScalarField, ValidationError, ValidationMes...
{ if alias.item == id_key && schema.field(field).name != id_key { Err(vec![ValidationError::new( ValidationMessage::DisallowIdAsAliasError(), vec![alias.location], )]) } else { Ok(()) } }
identifier_body
disallow_id_as_alias.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::WithLocation; use errors::try2; use graphql_ir::{ LinkedField, Program, ScalarField, ValidationError, ValidationMes...
<'s>(program: &'s Program<'s>) -> Vec<ValidationError> { let mut validator = DisallowIdAsAlias::new(program); match validator.validate_program(program) { Err(e) => e, Ok(_) => Default::default(), } } struct DisallowIdAsAlias<'s> { program: &'s Program<'s>, id_key: StringKey, } impl...
disallow_id_as_alias
identifier_name
borrowck-loan-in-overloaded-op.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = foo(~3); let _y = x + {x}; // the `{x}` forces a move to occur //~^ ERROR cannot move out of `x` }
main
identifier_name
borrowck-loan-in-overloaded-op.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn main() { let x = foo(~3); let _y = x + {x}; // the `{x}` forces a move to occur //~^ ERROR cannot move out of `x` }
{ let foo(~i) = *self; let foo(~j) = *f; foo(~(i + j)) }
identifier_body
borrowck-loan-in-overloaded-op.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
impl Add<foo, foo> for foo { fn add(&self, f: &foo) -> foo { let foo(~i) = *self; let foo(~j) = *f; foo(~(i + j)) } } fn main() { let x = foo(~3); let _y = x + {x}; // the `{x}` forces a move to occur //~^ ERROR cannot move out of `x` }
struct foo(~uint);
random_line_split
main.rs
extern crate rand; use std::fmt; use std::{thread, time}; use std::process; use rand::{thread_rng, Rng}; trait State : fmt::Display { fn do_clock(&self, hour: u32) -> Box<State>; fn do_use(&self, context: Box<&Context>); fn do_alarm(&self, context: Box<&Context>); fn do_phone(&self, context: Box<&Cont...
fn click_exit(&self) { process::exit(0); } } impl Context for SafeFrame { fn set_clock(&mut self, hour: u32) { println!("現在時刻は{0: >02}:00", hour); let state = self.state.do_clock(hour); if &self.state!= &state { self.change_state(state); } } ...
random_line_split
main.rs
extern crate rand; use std::fmt; use std::{thread, time}; use std::process; use rand::{thread_rng, Rng}; trait State : fmt::Display { fn do_clock(&self, hour: u32) -> Box<State>; fn do_use(&self, context: Box<&Context>); fn do_alarm(&self, context: Box<&Context>); fn do_phone(&self, context: Box<&Cont...
new("State Sample".to_string(), Box::new(NightState::new())); let mut rng = thread_rng(); println!("------------"); println!("{}", frame.title); println!("------------\n"); loop { for hour in 0..24 { frame.set_clock(hour); match rng.gen_range(0, 3) ...
n main() { let mut frame = SafeFrame::
identifier_body
main.rs
extern crate rand; use std::fmt; use std::{thread, time}; use std::process; use rand::{thread_rng, Rng}; trait State : fmt::Display { fn do_clock(&self, hour: u32) -> Box<State>; fn do_use(&self, context: Box<&Context>); fn do_alarm(&self, context: Box<&Context>); fn do_phone(&self, context: Box<&Cont...
9 <= hour && hour < 17 { Box::new(DayState::new()) } else { Box::new(NightState::new()) } } fn do_use(&self, context: Box<&Context>) { context.call_security_center("非常:夜間の金庫使用!".to_string()); } fn do_alarm(&self, context: Box<&Context>) { context...
if
identifier_name
dynamic_tests.rs
use crate::cell::RefCell; use crate::collections::HashMap; use crate::thread_local; #[test] fn smoke() { fn square(i: i32) -> i32 { i * i } thread_local!(static FOO: i32 = square(3)); FOO.with(|f| { assert_eq!(*f, 9); }); } #[test] fn hashmap()
#[test] fn refcell_vec() { thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3])); FOO.with(|vec| { assert_eq!(vec.borrow().len(), 3); vec.borrow_mut().push(4); assert_eq!(vec.borrow()[3], 4); }); }
{ fn map() -> RefCell<HashMap<i32, i32>> { let mut m = HashMap::new(); m.insert(1, 2); RefCell::new(m) } thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map()); FOO.with(|map| { assert_eq!(map.borrow()[&1], 2); }); }
identifier_body
dynamic_tests.rs
use crate::cell::RefCell; use crate::collections::HashMap; use crate::thread_local; #[test] fn smoke() { fn square(i: i32) -> i32 { i * i } thread_local!(static FOO: i32 = square(3)); FOO.with(|f| { assert_eq!(*f, 9); }); } #[test] fn hashmap() { fn map() -> RefCell<HashMap<i3...
FOO.with(|map| { assert_eq!(map.borrow()[&1], 2); }); } #[test] fn refcell_vec() { thread_local!(static FOO: RefCell<Vec<u32>> = RefCell::new(vec![1, 2, 3])); FOO.with(|vec| { assert_eq!(vec.borrow().len(), 3); vec.borrow_mut().push(4); assert_eq!(vec.borrow()[3], 4); ...
} thread_local!(static FOO: RefCell<HashMap<i32, i32>> = map());
random_line_split
dynamic_tests.rs
use crate::cell::RefCell; use crate::collections::HashMap; use crate::thread_local; #[test] fn smoke() { fn
(i: i32) -> i32 { i * i } thread_local!(static FOO: i32 = square(3)); FOO.with(|f| { assert_eq!(*f, 9); }); } #[test] fn hashmap() { fn map() -> RefCell<HashMap<i32, i32>> { let mut m = HashMap::new(); m.insert(1, 2); RefCell::new(m) } thread_local!(...
square
identifier_name
prefs.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 basedir::default_config_dir; use embedder_traits::resources::{self, Resource}; use num_cpus; use opts; use rus...
} pub fn default_prefs() -> Preferences { let prefs = Preferences(Arc::new(RwLock::new(HashMap::new()))); prefs.set( "layout.threads", PrefValue::Number(max(num_cpus::get() * 3 / 4, 1) as f64), ); prefs } pub fn read_prefs(txt: &str) -> Result<HashMap<String, Pref>, ()> { let json...
{ self.value().to_json() }
identifier_body
prefs.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 basedir::default_config_dir; use embedder_traits::resources::{self, Resource}; use num_cpus; use opts; use rus...
(&self) -> bool { self.get("dom.webgl2.enabled").as_boolean().unwrap_or(false) } }
is_webgl2_enabled
identifier_name
prefs.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 basedir::default_config_dir; use embedder_traits::resources::{self, Resource}; use num_cpus; use opts; use rus...
WithDefault(Arc<PrefValue>, Option<Arc<PrefValue>>), } impl Pref { pub fn new(value: PrefValue) -> Pref { Pref::NoDefault(Arc::new(value)) } fn new_default(value: PrefValue) -> Pref { Pref::WithDefault(Arc::new(value), None) } fn from_json(data: Json) -> Result<Pref, ()> { ...
} #[derive(Clone, Debug, Deserialize, Serialize)] pub enum Pref { NoDefault(Arc<PrefValue>),
random_line_split
preprocessor_tests.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ errors::*, preprocessor::{build_transactions, extract_global_config, split_input}, }; fn parse_input(input: &str) -> Result<()> { let config = extract_global_config("".lines(), false)?; let (_, transactions...
() { parse_input(r" main() {} //! new-transaction //! new-transaction main() {} ").unwrap_err(); } #[rustfmt::skip] #[test] fn parse_input_empty_transaction_with_config() { parse_input(r" main() {} //! new-transaction //! sender: default /...
parse_input_empty_transaction
identifier_name
preprocessor_tests.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ errors::*, preprocessor::{build_transactions, extract_global_config, split_input}, }; fn parse_input(input: &str) -> Result<()> { let config = extract_global_config("".lines(), false)?; let (_, transactions...
#[test] fn parse_input_no_transactions_with_config() { parse_input("//! no-run: verifier").unwrap_err(); } #[rustfmt::skip] #[test] fn parse_input_nothing_before_first_empty_transaction() { parse_input(r" //! new-transaction main() {} ").unwrap(); } #[rustfmt::skip] #[test] fn parse_inpu...
{ parse_input("").unwrap_err(); }
identifier_body
preprocessor_tests.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ errors::*, preprocessor::{build_transactions, extract_global_config, split_input}, };
build_transactions(&config, &transactions)?; Ok(()) } #[test] fn parse_input_no_transactions() { parse_input("").unwrap_err(); } #[test] fn parse_input_no_transactions_with_config() { parse_input("//! no-run: verifier").unwrap_err(); } #[rustfmt::skip] #[test] fn parse_input_nothing_before_first_empt...
fn parse_input(input: &str) -> Result<()> { let config = extract_global_config("".lines(), false)?; let (_, transactions) = split_input(input.lines(), &config)?;
random_line_split
boxes.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use std::fmt; macro_rules! box_database { ($($boxenum:ident $boxtype:expr),*,) => { #[derive(Clone, Copy...
impl From<u32> for BoxType { fn from(t: u32) -> BoxType { use self::BoxType::*; match t { $($boxtype => $boxenum),*, _ => UnknownBox(t), } } } impl Into<u32> for BoxType { ...
random_line_split
boxes.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use std::fmt; macro_rules! box_database { ($($boxenum:ident $boxtype:expr),*,) => { #[derive(Clone, Copy...
(t: BoxType) -> FourCC { let box_num: u32 = Into::into(t); From::from(box_num) } } impl<'a> From<&'a str> for FourCC { fn from(v: &'a str) -> FourCC { FourCC { value: v.to_owned() } } } impl fmt::Debug for FourCC { fn fmt(&self, f: &mut fmt::Formatter) -> fm...
from
identifier_name
boxes.rs
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use std::fmt; macro_rules! box_database { ($($boxenum:ident $boxtype:expr),*,) => { #[derive(Clone, Copy...
} impl From<BoxType> for FourCC { fn from(t: BoxType) -> FourCC { let box_num: u32 = Into::into(t); From::from(box_num) } } impl<'a> From<&'a str> for FourCC { fn from(v: &'a str) -> FourCC { FourCC { value: v.to_owned() } } } impl fmt::Debug for FourCC { ...
{ let mut box_chars = Vec::new(); for x in 0..4 { let c = (number >> (x * 8) & 0x0000_00FF) as u8; box_chars.push(c); } box_chars.reverse(); let box_string = match String::from_utf8(box_chars) { Ok(t) => t, _ => String::from("null"...
identifier_body
main.ng.rs
//! Multivariate linear regression using gradient descent //! //! Model: //! //! ``` //! y = x * theta + e //! //! y Dependent variable (scalar) //! x Independent variables (1-by-n matrix) //! theta Parameters to estimate (n-by-1 matrix) //! e Error (scalar) //! ``` //! //! Cost fu...
(path: &Path) -> io::Result<Transposed<Mat<f64>>> { let mut lines = Lines::from(BufReader::new(try!(File::open(path)))); let mut v = vec![]; let ncols = { let mut ncols = 0; for number in try!(lines.next().unwrap()).split_whitespace() { ncols += 1; ...
load
identifier_name
main.ng.rs
//! Multivariate linear regression using gradient descent //! //! Model: //! //! ``` //! y = x * theta + e //! //! y Dependent variable (scalar) //! x Independent variables (1-by-n matrix) //! theta Parameters to estimate (n-by-1 matrix) //! e Error (scalar) //! ``` //! //! Cost fu...
last_J = J; } max_niters } /// Loads data from a TSV file fn load<P>(path: P) -> io::Result<Transposed<Mat<f64>>> where P: AsRef<Path> { fn load(path: &Path) -> io::Result<Transposed<Mat<f64>>> { let mut lines = Lines::from(BufReader::new(try!(File::open(path)))); let mut v = ve...
{ return i }
conditional_block
main.ng.rs
//! Multivariate linear regression using gradient descent //! //! Model: //! //! ``` //! y = x * theta + e //! //! y Dependent variable (scalar) //! x Independent variables (1-by-n matrix) //! theta Parameters to estimate (n-by-1 matrix) //! e Error (scalar) //! ``` //! //! Cost fu...
let mut X = Mat::ones((m, n + 1)); X[.., 1..] = data[.., 1..]; let y = data.col(0); let (mu, sigma) = timeit!("Normalization", { normalize(&mut X[.., 1..]) }); println!("mean: {:?}", mu); println!("std deviation: {:?}\n", sigma); let ref mut theta = ColVec::zeros(n + 1); ...
{ env_logger::init().unwrap(); // Some dummy operation to force the initialization of OpenBLAS' runtime (~90 ms) here rather // than during the measurements below (&mat![1., 2.; 3., 4.].inv() * &mat![1., 2.; 3., 4.]).eval(); let data = timeit!("Loading data", { load("mpg.tsv").unwrap() ...
identifier_body
main.ng.rs
//! Multivariate linear regression using gradient descent //! //! Model: //! //! ``` //! y = x * theta + e //! //! y Dependent variable (scalar) //! x Independent variables (1-by-n matrix) //! theta Parameters to estimate (n-by-1 matrix) //! e Error (scalar) //! ``` //! //! Cost fu...
*col -= mean; *col /= sd; } (mu, sigma) } /// Performs the gradient descent algorithm to find the value of `theta` that minimizes the cost /// function. /// /// X (m, n) /// y (m, 1) /// theta (n, 1) /// alpha scalar Step size /// max_niters integer Maximum...
mu.push(mean); sigma.push(sd);
random_line_split
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread need...
{ id: PendingImageId, cache: Arc<ImageCache>, } impl FetchResponseListener for LayoutImageContext { fn process_request_body(&mut self) {} fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.cache.notify_pending_response(...
LayoutImageContext
identifier_name
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread need...
url: url, origin: document.origin().immutable().clone(), destination: Destination::Image, pipeline_id: Some(document.global().pipeline_id()), .. FetchRequestInit::default() }; // Layout image loads do not delay the document load event. document.loader().fetch_async_ba...
{ let context = Arc::new(Mutex::new(LayoutImageContext { id: id, cache: cache, })); let document = document_from_node(node); let window = document.window(); let (action_sender, action_receiver) = ipc::channel().unwrap(); let listener = NetworkListener { context: context...
identifier_body
layout_image.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/. */ //! Infrastructure to initiate network requests for images needed by the layout //! thread. The script thread need...
} fn process_response_eof(&mut self, response: Result<(), NetworkError>) { self.cache.notify_pending_response(self.id, FetchResponseMsg::ProcessResponseEOF(response)); } } impl PreInvoke for LayoutImageContext {} pub fn fetch_image_for_layout(url: ServoU...
FetchResponseMsg::ProcessResponseChunk(payload));
random_line_split
hkt_notes.rs
higher kinded types in rust struct List<A> {... } /* note we could fully apply this or use trait Functor for List {... } trait Functor for List<_> {... } fn (&self<A> Functor<A> for List when we implement a normal trait we have a hidden type parameter if we look at Haskell for example, a simple show class looks ...
(&self) -> String { self.clone() } } If we move to an example like: // Could be named anything, just keeping with Haskell // convention, this represents a container that can be mapped ove // class Functor f map :: (a -> b) -> f a -> f b instance Functor [] where map f [] = [] map f (x:xs) = f x : map f x...
show
identifier_name
hkt_notes.rs
higher kinded types in rust struct List<A> {... } /* note we could fully apply this or use trait Functor for List {... } trait Functor for List<_> {... } fn (&self<A> Functor<A> for List when we implement a normal trait we have a hidden type parameter if we look at Haskell for example, a simple show class looks ...
map f (x:xs) = f x : map f xs trait Functor where Self<_> {... } impl Functor for List
class Functor f map :: (a -> b) -> f a -> f b instance Functor [] where map f [] = []
random_line_split
lib.rs
//! Render to a window created by Glutin, using Glium's OpenGL functions #[macro_use] extern crate log; #[macro_use] extern crate glium; extern crate breeze_backend; use breeze_backend::{BackendAction, BackendResult, Renderer}; use breeze_backend::ppu::{SCREEN_WIDTH, SCREEN_HEIGHT}; use breeze_backend::viewport::View...
_ => {} } } Ok(vec![]) } } fn resize(vbuf: &mut VertexBuffer<Vertex>, win_w: u32, win_h: u32) { let Viewport { x, y, w, h } = Viewport::for_window_size(win_w, win_h); let (win_w, win_h) = (win_w as f32, win_h as f32); let (x, y, w, h) = (x as f32 / win_w, y...
{ resize(&mut self.vbuf, w, h); }
conditional_block
lib.rs
//! Render to a window created by Glutin, using Glium's OpenGL functions #[macro_use] extern crate log; #[macro_use] extern crate glium; extern crate breeze_backend; use breeze_backend::{BackendAction, BackendResult, Renderer}; use breeze_backend::ppu::{SCREEN_WIDTH, SCREEN_HEIGHT}; use breeze_backend::viewport::View...
format: ClientFormat::U8U8U8, }); let mut target = self.display.draw(); target.clear_color_srgb(0.0, 0.0, 0.0, 0.0); target.draw( &self.vbuf, &NoIndices(PrimitiveType::TriangleStrip), &self.program, &uniform! { ...
data: Cow::Borrowed(frame_data), width: SCREEN_WIDTH, height: SCREEN_HEIGHT,
random_line_split
lib.rs
//! Render to a window created by Glutin, using Glium's OpenGL functions #[macro_use] extern crate log; #[macro_use] extern crate glium; extern crate breeze_backend; use breeze_backend::{BackendAction, BackendResult, Renderer}; use breeze_backend::ppu::{SCREEN_WIDTH, SCREEN_HEIGHT}; use breeze_backend::viewport::View...
(&mut self, frame_data: &[u8]) -> BackendResult<Vec<BackendAction>> { // upload new texture data self.texture.write(Rect { left: 0, bottom: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT, }, RawImage2d { data: Cow::Borrowed(frame_data), ...
render
identifier_name
main.rs
extern crate itertools; use std::ops::Add; use itertools::Itertools; struct Character { hitpoints: u16, damage: u16, armor: u16 } impl Character { fn rounds(&self, opponent: &Character) -> u16 { let round_damage: f64 = if opponent.armor >= self.damage { 1 } else...
for inventory in inventories.iter() { additional.push(inventory + &rings.0); additional.push(inventory + &rings.1); additional.push(inventory + &(rings.0 + rings.1)); } } inventories.extend(additional); for inventory in &in...
let mut additional = Vec::with_capacity(rings.len() * 3); for rings in rings.iter().combinations() {
random_line_split
main.rs
extern crate itertools; use std::ops::Add; use itertools::Itertools; struct Character { hitpoints: u16, damage: u16, armor: u16 } impl Character { fn rounds(&self, opponent: &Character) -> u16 { let round_damage: f64 = if opponent.armor >= self.damage { 1 } els...
as f64; ((opponent.hitpoints as f64) / round_damage).ceil() as u16 } fn beats(&self, opponent: &Character) -> bool { let a = self.rounds(opponent); let b = opponent.rounds(&self); a <= b } } #[derive(Clone)] struct Inventory { cost: u16, damage: u16, armor:...
{ self.damage - opponent.armor }
conditional_block
main.rs
extern crate itertools; use std::ops::Add; use itertools::Itertools; struct
{ hitpoints: u16, damage: u16, armor: u16 } impl Character { fn rounds(&self, opponent: &Character) -> u16 { let round_damage: f64 = if opponent.armor >= self.damage { 1 } else { self.damage - opponent.armor } as f64; ((opponent.hitpoints as f64) / round...
Character
identifier_name
lib.rs
// Copyright 2021 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
#[cfg(feature = "allocator_api")] use core::alloc::AllocError; #[cfg(feature = "allocator_api")] use core::ptr::NonNull; #[cfg(feature = "allocator_api")] unsafe impl core::alloc::Allocator for GlobalScudoAllocator { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { let layout = fit...
pub fn print_stats() { unsafe { scudo_print_stats() } } }
random_line_split
lib.rs
// Copyright 2021 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
#[test] fn test_1byte_box_uses_scudo() { // Unlike the other arbitrary size allocations, it seems // Rust's test harness does have some 1 byte allocations so we cannot // assert there are 0, then 1, then 0. let before = count_allocations_by_size(1); let b = Box::new(1i...
{ assert_eq!(count_allocations_by_size(28), 0); let b = Box::new_in([3.0f32; 7], A); assert_eq!(count_allocations_by_size(28), 1); // Move b (move || b)(); assert_eq!(count_allocations_by_size(28), 0); }
identifier_body
lib.rs
// Copyright 2021 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
} /// Test-only function that returns the number of allocations of a given size. fn count_allocations_by_size(size: usize) -> usize { let mut size_and_count = (size, 0usize); unsafe { scudo_disable(); scudo_iterate( contains, &mut siz...
{ *count += 1; }
conditional_block
lib.rs
// Copyright 2021 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
() { // Unlike the other arbitrary size allocations, it seems // Rust's test harness does have some 1 byte allocations so we cannot // assert there are 0, then 1, then 0. let before = count_allocations_by_size(1); let b = Box::new(1i8); assert_eq!(count_allocations_by_siz...
test_1byte_box_uses_scudo
identifier_name
transit.rs
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, di...
() { let eq_point1 = coords::EqPoint{ asc: 40.68021_f64.to_radians(), dec: 18.04761_f64.to_radians() }; let eq_point2 = coords::EqPoint{ asc: 41.73129_f64.to_radians(), dec: 18.44092_f64.to_radians() }; let eq_point3 = coords::EqPoint{ asc: 42.78204_f64.to_ra...
time
identifier_name
transit.rs
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, di...
let Theta0 = 177.74208_f64.to_radians(); let deltaT = time::delta_t(1988, 3); let (h_rise, m_rise, s_rise) = transit::time( &transit::TransitType::Rise, &transit::TransitBody::StarOrPlanet, &geograph_point, &eq_point1, &eq_point2, &eq_point3, Theta0,...
{ let eq_point1 = coords::EqPoint{ asc: 40.68021_f64.to_radians(), dec: 18.04761_f64.to_radians() }; let eq_point2 = coords::EqPoint{ asc: 41.73129_f64.to_radians(), dec: 18.44092_f64.to_radians() }; let eq_point3 = coords::EqPoint{ asc: 42.78204_f64.to_radia...
identifier_body
transit.rs
/* Copyright (c) 2015, 2016 Saurav Sachidanand Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, di...
#![allow(non_snake_case)] extern crate astro; use astro::*; #[test] #[allow(unused_variables)] fn time() { let eq_point1 = coords::EqPoint{ asc: 40.68021_f64.to_radians(), dec: 18.04761_f64.to_radians() }; let eq_point2 = coords::EqPoint{ asc: 41.73129_f64.to_radians(), de...
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
random_line_split
gray.rs
/// Reads in a list of values and returns the gray codes of the length of each value /// Does so only up to the length of 64 bits (unsigned values) // io functions use std::io::prelude::*; use std::error::Error; use std::fs::File; use std::path::Path; use std::env; /// Decimal to Gray Code fn gray(num: u64) -> u64 {...
for val in vals { for gray in gray_length(val) { out(gray, 3); } } }
Ok(n) => parse(n), Err(why) => panic!("File could not be accessed {}", why), };
random_line_split
gray.rs
/// Reads in a list of values and returns the gray codes of the length of each value /// Does so only up to the length of 64 bits (unsigned values) // io functions use std::io::prelude::*; use std::error::Error; use std::fs::File; use std::path::Path; use std::env; /// Decimal to Gray Code fn gray(num: u64) -> u64 {...
fn main() { let args: Vec<String> = env::args().collect(); let path = Path::new(&args[1]); let vals = match get_input(path) { Ok(n) => parse(n), Err(why) => panic!("File could not be accessed {}", why), }; for val in vals { for gray in gray_length(val) { out(g...
{ let vals: Vec<u8> = contents.split("\n").map(|x| s_parser(x)).collect(); vals }
identifier_body
gray.rs
/// Reads in a list of values and returns the gray codes of the length of each value /// Does so only up to the length of 64 bits (unsigned values) // io functions use std::io::prelude::*; use std::error::Error; use std::fs::File; use std::path::Path; use std::env; /// Decimal to Gray Code fn gray(num: u64) -> u64 {...
() { let args: Vec<String> = env::args().collect(); let path = Path::new(&args[1]); let vals = match get_input(path) { Ok(n) => parse(n), Err(why) => panic!("File could not be accessed {}", why), }; for val in vals { for gray in gray_length(val) { out(gray, 3); ...
main
identifier_name
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn from_value(val: A) -> Future<A> { /*! * Create a future from a value. * * The value is immediately available and calling `get` later will * not block. */ Future {state: Forced(val)} } pub fn from_fn(f: ~fn() -> A) -> Future<A> { ...
{ /*! * Executes the future's closure and then returns a borrowed * pointer to the result. The borrowed pointer lasts as long as * the future. */ match self.state { Forced(ref v) => return v, Evaluating => fail2!("Recursive forcing of future!"), ...
identifier_body
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
do task::spawn_with((v, chan)) |(v, chan)| { chan.send(blk(v)); } Future::from_port(port) } } #[cfg(test)] mod test { use future::Future; use std::cell::Cell; use std::comm::oneshot; use std::task; #[test] fn test_from_value() { let mut f =...
* The closure and its argument will be moved into a new task. The * closure will be run and its result used as the value of the future. */ let (port, chan) = oneshot();
random_line_split
future.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let mut f = Future::spawn_with(~"gale", |s| { s }); assert_eq!(f.get(), ~"gale"); } #[test] #[should_fail] fn test_futurefail() { let mut f = Future::spawn(|| fail2!()); let _x: ~str = f.get(); } #[test] fn test_sendable_future() { let expected ...
test_spawn_with
identifier_name
object_safety.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 ...
{ /// e.g., `fn foo()` StaticMethod, /// e.g., `fn foo(&self, x: Self)` or `fn foo(&self) -> Self` ReferencesSelf, /// e.g., `fn foo<A>()` Generic, } pub fn is_object_safe<'tcx>(tcx: &ty::ctxt<'tcx>, trait_def_id: ast::DefId) -> bool { ...
MethodViolationCode
identifier_name
object_safety.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 foo(&self) -> Self::Y // OK, desugars to next example // fn foo(&self) -> <Self as Trait>::Y // OK // fn foo(&self) -> Self::X // OK, desugars to next example // fn foo(&self) -> <Self as SuperTrait>::X // OK // } // ``` // // However, it is not as simple as allowin...
// fn foo(&self) -> Option<Self> // bad
random_line_split
label_break_value_illegal_uses.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
//~ ERROR expected `{`, found `'b` } fn labeled_else() { if true {} else 'b: {} //~ ERROR expected `{`, found `'b` } fn labeled_match() { match false 'b: {} //~ ERROR expected one of `.`, `?`, `{`, or an operator } pub fn main() {}
'b: {}
conditional_block
label_break_value_illegal_uses.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() {}
random_line_split
label_break_value_illegal_uses.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{}
identifier_body
label_break_value_illegal_uses.rs
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { match false 'b: {} //~ ERROR expected one of `.`, `?`, `{`, or an operator } pub fn main() {}
labeled_match
identifier_name
initial.rs
use git::Config; use helpers; use author::Author; use author_selection::AuthorSelection; use xdg::BaseDirectories; use Result; use CannotProcede; pub fn initial() -> Result<Config> { let xdg_dirs = BaseDirectories::with_prefix("partners")?; let config_path = xdg_dirs.place_config_file("partners.cfg")?; i...
Ok(partners_config) }
{ partners_config.add_author(&author)?; }
conditional_block
initial.rs
use git::Config; use helpers; use author::Author; use author_selection::AuthorSelection; use xdg::BaseDirectories; use Result; use CannotProcede; pub fn initial() -> Result<Config> { let xdg_dirs = BaseDirectories::with_prefix("partners")?; let config_path = xdg_dirs.place_config_file("partners.cfg")?;
if helpers::confirm("do you want to create it?")? { helpers::create_config_file(&config_path)?; } else { Err(CannotProcede)?; } } let partners_config = Config::File(config_path); let author = match Config::Local.current_author() { Ok(author) => autho...
if !config_path.exists() { println!("config file not found at {:?}", config_path);
random_line_split
initial.rs
use git::Config; use helpers; use author::Author; use author_selection::AuthorSelection; use xdg::BaseDirectories; use Result; use CannotProcede; pub fn initial() -> Result<Config>
println!("It seems like the current git author is not known to partners"); let nick = Config::Local.nick().or_else(|_| { println!("Please enter a nickname you would like to use"); helpers::query_required("Nick") })?; let name = Config::Lo...
{ let xdg_dirs = BaseDirectories::with_prefix("partners")?; let config_path = xdg_dirs.place_config_file("partners.cfg")?; if !config_path.exists() { println!("config file not found at {:?}", config_path); if helpers::confirm("do you want to create it?")? { helpers::create_con...
identifier_body
initial.rs
use git::Config; use helpers; use author::Author; use author_selection::AuthorSelection; use xdg::BaseDirectories; use Result; use CannotProcede; pub fn
() -> Result<Config> { let xdg_dirs = BaseDirectories::with_prefix("partners")?; let config_path = xdg_dirs.place_config_file("partners.cfg")?; if!config_path.exists() { println!("config file not found at {:?}", config_path); if helpers::confirm("do you want to create it?")? { ...
initial
identifier_name
mod.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/. */ #[cfg(any(target_os = "linux", target_os = "android"))] pub use crate::platform::freetype::{font, font_context}; ...
#[cfg(target_os = "macos")] pub use crate::platform::macos::{font, font_context, font_list, font_template}; #[cfg(any(target_os = "linux", target_os = "android"))] mod freetype { use libc::c_char; use std::ffi::CStr; use std::str; /// Creates a String from the given null-terminated buffer. /// Pa...
#[cfg(target_os = "windows")] pub use crate::platform::windows::{font, font_context, font_list, font_template};
random_line_split
mod.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/. */ #[cfg(any(target_os = "linux", target_os = "android"))] pub use crate::platform::freetype::{font, font_context}; ...
pub mod font; pub mod font_context; #[cfg(target_os = "linux")] pub mod font_list; #[cfg(target_os = "android")] mod android { pub mod font_list; } #[cfg(target_os = "android")] pub use self::android::font_list; #[cfg(any(target_os = "linux", target_os = "android"))] ...
{ str::from_utf8(CStr::from_ptr(s).to_bytes()) .unwrap() .to_owned() }
identifier_body
mod.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/. */ #[cfg(any(target_os = "linux", target_os = "android"))] pub use crate::platform::freetype::{font, font_context}; ...
(s: *const c_char) -> String { str::from_utf8(CStr::from_ptr(s).to_bytes()) .unwrap() .to_owned() } pub mod font; pub mod font_context; #[cfg(target_os = "linux")] pub mod font_list; #[cfg(target_os = "android")] mod android { pub mod font_list; } ...
c_str_to_string
identifier_name
base.rs
if let (Some(args), Some(meta_args)) = (&mut args, meta_args) { for arg in meta_args { let arg_name = arg.name.as_str(); if args.get(arg_name).map_or(true, InputValue::is_null) { if let Some(val) = arg.default_value.as_ref() { a...
/// # Example /// /// This trait is intended to be used in a conjunction with a [`GraphQLType`] trait. See the example /// in the documentation of a [`GraphQLType`] trait. /// /// [1]: https://spec.graphql.org/June2018/#sec-Interfaces /// [2]: https://spec.graphql.org/June2018/#sec-Unions /// [3]: https://spec.graphql....
/// resolving GraphQL values even when a concrete Rust type is erased. ///
random_line_split
base.rs
if let (Some(args), Some(meta_args)) = (&mut args, meta_args) { for arg in meta_args { let arg_name = arg.name.as_str(); if args.get(arg_name).map_or(true, InputValue::is_null) { if let Some(val) = arg.default_value.as_ref() { ar...
{ let sub_result = instance.resolve_into_type( info, &concrete_type_name, Some(&fragment.selection_set[..]), &sub_exec, ); if let Ok(Value::Object(...
{ if is_excluded(&spread.directives, executor.variables()) { continue; } let fragment = &executor .fragment_by_name(spread.name.item) .expect("Fragment could not be found"); let sub_exec = execu...
conditional_block
base.rs
if let (Some(args), Some(meta_args)) = (&mut args, meta_args) { for arg in meta_args { let arg_name = arg.name.as_str(); if args.get(arg_name).map_or(true, InputValue::is_null) { if let Some(val) = arg.default_value.as_ref() { ar...
/// Returns the concrete [`GraphQLType`] name for this [`GraphQLValue`] being an [interface][1], /// an [union][2] or an [object][3]. /// /// # Panics /// /// The default implementation panics. /// /// [1]: https://spec.graphql.org/June2018/#sec-Interfaces /// [2]: https://spec.gra...
{ if self.type_name(info).unwrap() == type_name { self.resolve(info, selection_set, executor) } else { panic!( "GraphQLValue::resolve_into_type() must be implemented by unions and interfaces" ); } }
identifier_body
base.rs
{ /// ## Scalar types /// /// Scalar types appear as the leaf nodes of GraphQL queries. Strings,\ /// numbers, and booleans are the built in types, and while it's possible\ /// to define your own, it's relatively uncommon. Scalar, /// ## Object types /// /// The most common type to...
TypeKind
identifier_name
error.rs
// Copyright 2016 evic Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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 according to th...
(error: io::Error) -> Error { Error::Io(error) } }
from
identifier_name
error.rs
// Copyright 2016 evic Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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 according to th...
} impl error::Error for Error { fn description(&self) -> &str { match *self { Error::Io(..) => "eVic IO error", Error::Firmware(..) => "eVic firmware error", Error::CliError(..) => "eVic CLI error", } } fn cause(&self) -> Option<&error::Error> { ...
{ match *self { Error::Io(ref err) => write!(f, "IO error: {}", err), Error::Firmware(ref err) => write!(f, "Firmware error: {}", err), Error::CliError(ref err) => write!(f, "CLI error: {}", err), } }
identifier_body
error.rs
// Copyright 2016 evic Developers // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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 according to th...
}
}
random_line_split
key_templates.rs
// Copyright 2020 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...
// //////////////////////////////////////////////////////////////////////////////// //! This module contains pre-generated [`KeyTemplate`] instances for deterministic AEAD. use tink_proto::{prost::Message, KeyTemplate}; /// Return a [`KeyTemplate`](tink_proto::KeyTemplate) that generates a AES-SIV key. pub fn aes_si...
// limitations under the License.
random_line_split
key_templates.rs
// Copyright 2020 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...
() -> KeyTemplate { let format = tink_proto::AesSivKeyFormat { key_size: 64, version: crate::AES_SIV_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: crate::AES_SIV_TYPE_URL.t...
aes_siv_key_template
identifier_name
key_templates.rs
// Copyright 2020 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 format = tink_proto::AesSivKeyFormat { key_size: 64, version: crate::AES_SIV_KEY_VERSION, }; let mut serialized_format = Vec::new(); format.encode(&mut serialized_format).unwrap(); // safe: proto-encode KeyTemplate { type_url: crate::AES_SIV_TYPE_URL.to_string(), ...
identifier_body
response.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
assert_eq!(verify(&headers, &request), Err(BasicError::WrongSkip(5, Some(2)))); } }
let mut header = Header::default(); header.set_number(x); encoded::Header::new(::rlp::encode(&header).into_vec()) }).collect();
random_line_split
response.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&self, headers: &[Header], _reverse: bool) -> Result<(), BasicError> { match headers.len() > self.0 { true => Err(BasicError::TooManyHeaders(self.0, headers.len())), false => Ok(()) } } } #[cfg(test)] mod tests { use ethcore::encoded; use ethcore::header::Header; use light::request::CompleteHeadersReque...
verify
identifier_name
response.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
}).collect(); assert!(verify(&headers, &request).is_ok()); } #[test] fn sequential_backward() { let request = HeadersRequest { start: 34.into(), max: 30, skip: 0, reverse: true, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).rev().map(|x| { let mut header ...
{ let request = HeadersRequest { start: 10.into(), max: 30, skip: 0, reverse: false, }; let mut parent_hash = None; let headers: Vec<_> = (0..25).map(|x| x + 10).map(|x| { let mut header = Header::default(); header.set_number(x); if let Some(parent_hash) = parent_hash { header.set_par...
identifier_body