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
classes-cross-crate.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 mut nyan = cat(0u, 2, ~"nyan"); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
identifier_body
classes-cross-crate.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 mut nyan = cat(0u, 2, ~"nyan"); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
main
identifier_name
classes-cross-crate.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...
pub fn main() { let mut nyan = cat(0u, 2, ~"nyan"); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
random_line_split
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
RTF: TReadTransportFactory +'static, IPF: TInputProtocolFactory +'static, WTF: TWriteTransportFactory +'static, OPF: TOutputProtocolFactory +'static, { r_trans_factory: RTF, i_proto_factory: IPF, w_trans_factory: WTF, o_proto_factory: OPF, processor: Arc<PRC>, worker_pool: Thread...
where PRC: TProcessor + Send + Sync + 'static,
random_line_split
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
} }
{ warn!("processor completed with error: {:?}", e); break; }
conditional_block
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
/// Listen for incoming connections on `listen_address`. /// /// `listen_address` should be in the form `host:port`, /// for example: `127.0.0.1:8080`. /// /// Return `()` if successful. /// /// Return `Err` when the server cannot bind to `listen_address` or there /// is an unrecov...
{ TServer { r_trans_factory: read_transport_factory, i_proto_factory: input_protocol_factory, w_trans_factory: write_transport_factory, o_proto_factory: output_protocol_factory, processor: Arc::new(processor), worker_pool: ThreadPool::with_...
identifier_body
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
<PRC>( processor: Arc<PRC>, i_prot: Box<TInputProtocol>, o_prot: Box<TOutputProtocol>, ) where PRC: TProcessor, { let mut i_prot = i_prot; let mut o_prot = o_prot; loop { let r = processor.process(&mut *i_prot, &mut *o_prot); if let Err(e) = r { warn!("processor c...
handle_incoming_connection
identifier_name
edit.rs
#![allow(deprecated)] use gpgme; use std::io::prelude::*; use gpgme::{ edit::{self, EditInteractionStatus, Editor}, Error, Result, }; use self::common::passphrase_cb; #[macro_use] mod common; #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum TestEditorState { Start, Fingerprint, Expire, Val...
Ok(State::Quit) => state, Ok(State::Primary) | Err(_) => Ok(State::Quit), _ => Err(Error::GENERAL), } } else if (status.args() == Ok(edit::KEY_VALID)) && (state == Ok(State::Expire)) { Ok(State::Valid) } else if (status.args() == Ok...
Ok(State::Start) => Ok(State::Fingerprint), Ok(State::Fingerprint) => Ok(State::Expire), Ok(State::Valid) => Ok(State::Uid), Ok(State::Uid) => Ok(State::Primary),
random_line_split
edit.rs
#![allow(deprecated)] use gpgme; use std::io::prelude::*; use gpgme::{ edit::{self, EditInteractionStatus, Editor}, Error, Result, }; use self::common::passphrase_cb; #[macro_use] mod common; #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum TestEditorState { Start, Fingerprint, Expire, Val...
( state: Result<Self::State>, status: EditInteractionStatus<'_>, need_response: bool, ) -> Result<Self::State> { use self::TestEditorState as State; println!("[-- Code: {:?}, {:?} --]", status.code, status.args()); if!need_response { return state; } if s...
next_state
identifier_name
derive.rs
use crate::cfg_eval::cfg_eval; use rustc_ast as ast; use rustc_ast::{attr, token, GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, StmtKind}; use rustc_errors::{struct_span_err, Applicability}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier}; use rustc_feature::A...
fn report_path_args(sess: &Session, meta: &ast::MetaItem) { let report_error = |title, action| { let span = meta.span.with_lo(meta.path.span.hi()); sess.struct_span_err(span, title) .span_suggestion(span, action, String::new(), Applicability::MachineApplicable) .emit(); }...
{ let help_msg = match lit.token.kind { token::Str if rustc_lexer::is_ident(&lit.token.symbol.as_str()) => { format!("try using `#[derive({})]`", lit.token.symbol) } _ => "for example, write `#[derive(Debug)]` for `Debug`".to_string(), }; struct_span_err!(sess, lit.span, ...
identifier_body
derive.rs
use crate::cfg_eval::cfg_eval; use rustc_ast as ast; use rustc_ast::{attr, token, GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, StmtKind}; use rustc_errors::{struct_span_err, Applicability}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier}; use rustc_feature::A...
( &self, ecx: &mut ExtCtxt<'_>, span: Span, meta_item: &ast::MetaItem, item: Annotatable, ) -> ExpandResult<Vec<Annotatable>, Annotatable> { let sess = ecx.sess; if report_bad_target(sess, &item, span) { // We don't want to pass inappropriate targe...
expand
identifier_name
derive.rs
use crate::cfg_eval::cfg_eval; use rustc_ast as ast; use rustc_ast::{attr, token, GenericParamKind, ItemKind, MetaItemKind, NestedMetaItem, StmtKind}; use rustc_errors::{struct_span_err, Applicability}; use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, Indeterminate, MultiItemModifier}; use rustc_feature::A...
[(_, first_item, _), others @..] => { *first_item = cfg_eval(sess, features, item.clone()); for (_, item, _) in others { *item = first_item.clone(); } } } ...
// Do not configure or clone items unless necessary. match &mut resolutions[..] { [] => {}
random_line_split
mock_engine.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; use crate::storage::kv::{Callback, ExtCallback, Modify, SnapContext, WriteData}; use crate::storage::{Engine, RocksEngine}; use kvproto::kvrpcpb::Context; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; /// A mock eng...
(&self) -> Self::Local { self.base.kv_engine() } fn snapshot_on_kv_engine(&self, start_key: &[u8], end_key: &[u8]) -> Result<Self::Snap> { self.base.snapshot_on_kv_engine(start_key, end_key) } fn modify_on_kv_engine(&self, modifies: Vec<Modify>) -> Result<()> { self.base.modify...
kv_engine
identifier_name
mock_engine.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; use crate::storage::kv::{Callback, ExtCallback, Modify, SnapContext, WriteData}; use crate::storage::{Engine, RocksEngine}; use kvproto::kvrpcpb::Context; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; /// A mock eng...
pub fn add_expected_write(mut self, write: ExpectedWrite) -> Self { self.expected_modifies.push_back(write); self } pub fn build(self) -> MockEngine { MockEngine { base: self.base, expected_modifies: Arc::new(ExpectedWriteList(Mutex::new(self.expected_modifi...
}
random_line_split
mock_engine.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; use crate::storage::kv::{Callback, ExtCallback, Modify, SnapContext, WriteData}; use crate::storage::{Engine, RocksEngine}; use kvproto::kvrpcpb::Context; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; /// A mock eng...
// check whether use right callback match expected_write.use_proposed_cb { Some(true) => assert!( proposed_cb.is_some(), "this write is supposed to return during the propose stage" ), ...
{ assert_eq!( modify, &expected_modify, "modify writing to Engine not match with expected" ) }
conditional_block
mock_engine.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use super::Result; use crate::storage::kv::{Callback, ExtCallback, Modify, SnapContext, WriteData}; use crate::storage::{Engine, RocksEngine}; use kvproto::kvrpcpb::Context; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; /// A mock eng...
fn async_write_ext( &self, ctx: &Context, batch: WriteData, write_cb: Callback<()>, proposed_cb: Option<ExtCallback>, committed_cb: Option<ExtCallback>, ) -> Result<()> { let mut expected_writes = self.expected_modifies.0.lock().unwrap(); for mod...
{ self.async_write_ext(ctx, batch, write_cb, None, None) }
identifier_body
mtwt.rs
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 those terms. //! Machinery for hygienic macros, as described in the MTWT[1] paper. //! //! [1] Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bru...
fn unfold_marks(mrks: Vec<Mrk>, tail: SyntaxContext, table: &SCTable) -> SyntaxContext { mrks.iter().rev().fold(tail, |tail:SyntaxContext, mrk:&Mrk| {new_mark_internal(*mrk,tail,table)}) } #[test] fn unfold_marks_test() { let mut t = new_sctable_intern...
// extend a syntax context with a sequence of marks given // in a vector. v[0] will be the outermost mark.
random_line_split
mtwt.rs
license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Machinery for hygienic macros, as described in the MTWT[1] paper. //! //! [1] Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce F...
else { marks.push(mark); } } #[cfg(test)] mod tests { use ast::*; use super::{resolve, xorPush, new_mark_internal, new_sctable_internal}; use super::{new_rename_internal, marksof_internal, resolve_internal}; use super::{SCTable, EmptyCtxt, Mark, Rename, IllegalCtxt}; use collections::H...
{ marks.pop().unwrap(); }
conditional_block
mtwt.rs
license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Machinery for hygienic macros, as described in the MTWT[1] paper. //! //! [1] Matthew Flatt, Ryan Culpepper, David Darais, and Robert Bruce F...
() { let stopname = 242; let name1 = 243; let mut t = new_sctable_internal(); assert_eq!(marksof_internal (EMPTY_CTXT,stopname,&t),Vec::new()); // FIXME #5074: ANF'd to dodge nested calls { let ans = unfold_marks(vec!(4,98),EMPTY_CTXT,&mut t); assert_eq! (markso...
test_marksof
identifier_name
auth.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::{sleep_with_handle, FailReasonExt, GMsg, RequestExt, Route, SessionExt}; use futures::channel::oneshot; use iml_wire_types::{EndpointName, Session}; use reg...
() -> Option<String> { let html_doc: HtmlDocument = HtmlDocument::from(JsValue::from(document())); let cookie = html_doc.cookie().unwrap(); parse_cookie(&cookie) } /// Parses the CSRF token out of the cookie if one exists. fn parse_cookie(cookie: &str) -> Option<String> { let re = Regex::new(r"csrftok...
csrf_token
identifier_name
auth.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::{sleep_with_handle, FailReasonExt, GMsg, RequestExt, Route, SessionExt}; use futures::channel::oneshot; use iml_wire_types::{EndpointName, Session}; use reg...
#[allow(clippy::large_enum_variant)] #[derive(Clone, Debug)] pub enum Msg { Fetch, Fetched(fetch::FetchObject<Session>), Logout, LoggedIn, Loop, Noop, } pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) { match msg { Msg::Fetch => { model.ca...
pub(crate) fn get_session(&self) -> Option<&Session> { self.session.as_ref() } }
random_line_split
auth.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::{sleep_with_handle, FailReasonExt, GMsg, RequestExt, Route, SessionExt}; use futures::channel::oneshot; use iml_wire_types::{EndpointName, Session}; use reg...
Ok(resp) => { model.session = Some(resp.data); if model.session.as_ref().unwrap().needs_login() { orders.send_g_msg(GMsg::RouteChange(Route::Login.into())); } else { orders.send_msg(Msg::Loop); ...
{ log!(format!("Error during session poll: {}", fail_reason.message())); orders.skip().send_msg(Msg::Loop); }
conditional_block
generic-function.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
// gdb-check:$3 = {{1, 2.5}, {2.5, 1}} // gdb-command:continue // gdb-command:finish // gdb-command:print *t0 // gdb-check:$4 = 3.5 // gdb-command:print *t1 // gdb-check:$5 = 4 // gdb-command:print ret // gdb-check:$6 = {{3.5, 4}, {4, 3.5}} // gdb-command:continue // gdb-command:finish // gdb-command:print *t0 // gdb...
// gdb-command:print *t0 // gdb-check:$1 = 1 // gdb-command:print *t1 // gdb-check:$2 = 2.5 // gdb-command:print ret
random_line_split
generic-function.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() {()}
zzz
identifier_name
bin.rs
#[macro_use] extern crate malachite_base_test_util; extern crate malachite_nz; extern crate malachite_nz_test_util; extern crate serde; extern crate serde_json; use demo_and_bench::register; use generate::digits_data::generate_string_data; use malachite_base_test_util::runner::cmd::read_command_line_arguments; use mal...
} } mod demo_and_bench; mod generate;
{ let args = read_command_line_arguments("malachite-nz test utils"); let mut runner = Runner::new(); register(&mut runner); if let Some(demo_key) = args.demo_key { runner.run_demo(&demo_key, args.generation_mode, args.config, args.limit); } else if let Some(bench_key) = args.bench_key { ...
identifier_body
bin.rs
#[macro_use] extern crate malachite_base_test_util; extern crate malachite_nz; extern crate malachite_nz_test_util; extern crate serde; extern crate serde_json; use demo_and_bench::register; use generate::digits_data::generate_string_data; use malachite_base_test_util::runner::cmd::read_command_line_arguments; use mal...
() { let args = read_command_line_arguments("malachite-nz test utils"); let mut runner = Runner::new(); register(&mut runner); if let Some(demo_key) = args.demo_key { runner.run_demo(&demo_key, args.generation_mode, args.config, args.limit); } else if let Some(bench_key) = args.bench_key { ...
main
identifier_name
bin.rs
#[macro_use] extern crate malachite_base_test_util; extern crate malachite_nz; extern crate malachite_nz_test_util; extern crate serde; extern crate serde_json; use demo_and_bench::register; use generate::digits_data::generate_string_data; use malachite_base_test_util::runner::cmd::read_command_line_arguments; use mal...
let codegen_key = args.codegen_key.unwrap(); match codegen_key.as_str() { "digits_data" => generate_string_data(), _ => panic!("Invalid codegen key: {}", codegen_key), } } } mod demo_and_bench; mod generate;
random_line_split
types.rs
use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::str::SplitWhitespace; pub type Params<'a> = SplitWhitespace<'a>; pub type Flag = Arc<AtomicBool>; pub const BK_CASTLE: u8 = 1; pub const WK_CASTLE: u8 = BK_CASTLE << WHITE; pub const BQ_CASTLE: u8 = 1 << 2; pub const WQ_CASTLE: u8 = BQ_CASTLE << WHITE; ...
pub const PVALS: [u32; 12] = [1000, 1000, 4126, 4126, 4222, 4222, 6414, 6414, 12730, 12730, 300000, 300000]; pub fn p_val(piece: u8) -> u32 { match piece { ...
{ c ^ WHITE }
identifier_body
types.rs
use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::str::SplitWhitespace; pub type Params<'a> = SplitWhitespace<'a>; pub type Flag = Arc<AtomicBool>; pub const BK_CASTLE: u8 = 1; pub const WK_CASTLE: u8 = BK_CASTLE << WHITE; pub const BQ_CASTLE: u8 = 1 << 2; pub const WQ_CASTLE: u8 = BQ_CASTLE << WHITE; ...
(c: u8) -> u8 { c ^ WHITE } pub const PVALS: [u32; 12] = [1000, 1000, 4126, 4126, 4222, 4222, 6414, 6414, 12730, 12730, 300000, 300000]; pub fn p_val(piece: u8) -> ...
flip
identifier_name
types.rs
use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::str::SplitWhitespace; pub type Params<'a> = SplitWhitespace<'a>; pub type Flag = Arc<AtomicBool>; pub const BK_CASTLE: u8 = 1; pub const WK_CASTLE: u8 = BK_CASTLE << WHITE; pub const BQ_CASTLE: u8 = 1 << 2; pub const WQ_CASTLE: u8 = BQ_CASTLE << WHITE; ...
pub const PVALS: [u32; 12] = [1000, 1000, 4126, 4126, 4222, 4222, 6414, 6414, 12730, 12730, 300000, 300000]; pub fn p_val(piece: u8) -> u32 { match piece { ...
random_line_split
peer.rs
use ::address::PublicKey; use super::{ ffi, error, vars, Group, Status }; use super::status::{ Connection, UserStatus }; /// GropuChat Peer. #[derive(Clone, Debug)] pub struct Peer { pub group: Group, pub number: i32 } impl Peer { pub fn from(group: &Group, number: i32) -> Peer { Peer...
; let name_len = lengths[self.number as usize]; Ok(names[self.number as usize][..name_len as usize].into()) } // fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { // let mut name = unsafe { vec_with!(vars::TOX_MAX_NAME_LENGTH) }; // match unsafe { ffi::tox_group_peername(...
{ return Err(error::GetStatusErr::Group); }
conditional_block
peer.rs
use ::address::PublicKey; use super::{ ffi, error, vars, Group, Status }; use super::status::{ Connection, UserStatus }; /// GropuChat Peer. #[derive(Clone, Debug)] pub struct Peer { pub group: Group, pub number: i32 } impl Peer { pub fn from(group: &Group, number: i32) -> Peer { Peer...
} impl Status for Peer { fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { let len = unsafe { ffi::tox_group_number_peers( self.group.core, self.group.number ) }; let mut names = unsafe { vec_with!(len as usize) }; let mut lengths = unsafe { vec_with!...
{ unsafe { ffi::tox_group_peernumber_is_ours( self.group.core, self.group.number, self.number ) != 0 } }
identifier_body
peer.rs
use ::address::PublicKey; use super::{ ffi, error, vars, Group, Status }; use super::status::{ Connection, UserStatus }; /// GropuChat Peer. #[derive(Clone, Debug)] pub struct Peer { pub group: Group, pub number: i32 } impl Peer { pub fn from(group: &Group, number: i32) -> Peer { Peer...
(&self) -> Result<PublicKey, error::GetStatusErr> { let mut pk = unsafe { vec_with!(vars::TOX_PUBLIC_KEY_SIZE) }; match unsafe { ffi::tox_group_peer_pubkey( self.group.core, self.group.number, self.number, pk.as_mut_ptr() ) } { -1 => Er...
publickey
identifier_name
peer.rs
use ::address::PublicKey; use super::{ ffi, error, vars, Group, Status }; use super::status::{ Connection, UserStatus }; /// GropuChat Peer. #[derive(Clone, Debug)] pub struct Peer { pub group: Group, pub number: i32 } impl Peer { pub fn from(group: &Group, number: i32) -> Peer { Peer...
}; let name_len = lengths[self.number as usize]; Ok(names[self.number as usize][..name_len as usize].into()) } // fn name(&self) -> Result<Vec<u8>, error::GetStatusErr> { // let mut name = unsafe { vec_with!(vars::TOX_MAX_NAME_LENGTH) }; // match unsafe { ffi::tox_group_...
random_line_split
underscore.rs
use std::old_io::{stdout, stderr}; use libc::pid_t; use argparse::{ArgumentParser}; use argparse::{StoreTrue, StoreFalse, List, StoreOption, Store}; use config::Config; use config::command::{CommandInfo, Networking}; use container::container::Namespace::{NewUser, NewNet}; use container::nsutil::{set_namespace}; use ...
"); ap.refer(&mut container) .add_argument("container", Store, "Container to run command in") .required(); ap.refer(&mut cmdargs) .add_argument("command", List, "Command (with arguments) to run inside container") ...
random_line_split
underscore.rs
use std::old_io::{stdout, stderr}; use libc::pid_t; use argparse::{ArgumentParser}; use argparse::{StoreTrue, StoreFalse, List, StoreOption, Store}; use config::Config; use config::command::{CommandInfo, Networking}; use container::container::Namespace::{NewUser, NewNet}; use container::nsutil::{set_namespace}; use ...
"Command (with arguments) to run inside container") .required(); ap.stop_on_first_argument(true); match ap.parse(args, &mut stdout(), &mut stderr()) { Ok(()) => {} Err(0) => return Ok(0), Err(_) => { return Ok(122); ...
{ let mut cmdargs = vec!(); let mut container = "".to_string(); let mut pid = None; { args.insert(0, "vagga ".to_string() + cname.as_slice()); let mut ap = ArgumentParser::new(); ap.set_description( "Run command (or shell) in one of the vagga's network namespaces"); ...
identifier_body
underscore.rs
use std::old_io::{stdout, stderr}; use libc::pid_t; use argparse::{ArgumentParser}; use argparse::{StoreTrue, StoreFalse, List, StoreOption, Store}; use config::Config; use config::command::{CommandInfo, Networking}; use container::container::Namespace::{NewUser, NewNet}; use container::nsutil::{set_namespace}; use ...
(config: &Config, workdir: &Path, cname: String, mut args: Vec<String>) -> Result<i32, String> { let mut cmdargs = vec!(); let mut container = "".to_string(); let mut pid = None; { args.insert(0, "vagga ".to_string() + cname.as_slice()); let mut ap = ArgumentParser::new(); ...
run_in_netns
identifier_name
issue-5806.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // opyright 2013 Th...
//
random_line_split
issue-5806.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 ...
{}
identifier_body
issue-5806.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 ...
() {}
main
identifier_name
types.rs
use self::ItemType::*; use std::io; use std::io::Write; use str::GopherStr; use bytes::Bytes; /// A client-to-server message. #[derive(Clone, Debug)] pub struct GopherRequest { /// Identifier of the resource to fetch. May be an empty string. pub selector: GopherStr, /// Search string for a full-text search...
{ pub entities: Vec<DirEntity>, } /// An menu item in a directory of Gopher resources. #[derive(Clone, Debug)] pub struct DirEntity { /// The type of the resource pub item_type: ItemType, /// String to display to the user. pub name: GopherStr, /// Path or identifier used for requesting this re...
Menu
identifier_name
types.rs
use self::ItemType::*; use std::io; use std::io::Write; use str::GopherStr; use bytes::Bytes; /// A client-to-server message. #[derive(Clone, Debug)] pub struct GopherRequest { /// Identifier of the resource to fetch. May be an empty string. pub selector: GopherStr, /// Search string for a full-text search...
/// A list of resources. Menu(Vec<DirEntity>), /// A text document. TextFile(Bytes), /// A binary file download. BinaryFile(Bytes), /// A single menu item enclosed in a Gopher+ protocol response. /// /// Useful for redirecting Gopher+ clients to the standard Gopher protocol. G...
} /// A server-to-client message. #[derive(Clone, Debug)] pub enum GopherResponse {
random_line_split
fps.rs
use time::precise_time_ns; // FPS is smoothed with an exponentially-weighted moving average. // This is the proportion of the old FPS to keep on each step. const SMOOTHING: f32 = 0.9; // How often to output FPS, in milliseconds. const OUTPUT_INTERVAL: u64 = 5_000; pub struct FPSTracker { last_frame_time:...
() -> FPSTracker { let t = precise_time_ns(); FPSTracker { last_frame_time: t, last_fps_output_time: t, smoothed_fps: 0.0, } } pub fn tick(&mut self) { let this_frame_time = precise_time_ns(); let instant_fps = 1e9 / ((this_frame_time ...
new
identifier_name
fps.rs
use time::precise_time_ns; // FPS is smoothed with an exponentially-weighted moving average. // This is the proportion of the old FPS to keep on each step. const SMOOTHING: f32 = 0.9; // How often to output FPS, in milliseconds. const OUTPUT_INTERVAL: u64 = 5_000; pub struct FPSTracker { last_frame_time:...
} } pub fn tick(&mut self) { let this_frame_time = precise_time_ns(); let instant_fps = 1e9 / ((this_frame_time - self.last_frame_time) as f32); self.smoothed_fps = SMOOTHING * self.smoothed_fps + (1.0-SMOOTHING) * instant_fps; self.last_frame_time =...
let t = precise_time_ns(); FPSTracker { last_frame_time: t, last_fps_output_time: t, smoothed_fps: 0.0,
random_line_split
fps.rs
use time::precise_time_ns; // FPS is smoothed with an exponentially-weighted moving average. // This is the proportion of the old FPS to keep on each step. const SMOOTHING: f32 = 0.9; // How often to output FPS, in milliseconds. const OUTPUT_INTERVAL: u64 = 5_000; pub struct FPSTracker { last_frame_time:...
} }
{ println!("Frames per second: {:7.2}", self.smoothed_fps); self.last_fps_output_time = this_frame_time; }
conditional_block
lib.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(missing_docs)] //! The library crate that defines common helper functions that are generally used in //! conjunction with seccompiler-bin. mod common; use bincode::Error as BincodeError; use binc...
() { // Malformed bincode binary. { let data = "adassafvc".to_string(); assert!(deserialize_binary(data.as_bytes(), None).is_err()); } // Test that the binary deserialization is correct, and that the thread keys // have been lowercased. { ...
test_deserialize_binary
identifier_name
lib.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(missing_docs)] //! The library crate that defines common helper functions that are generally used in //! conjunction with seccompiler-bin. mod common; use bincode::Error as BincodeError; use binc...
// Binary limit too low. assert!(matches!( deserialize_binary(&bytes[..], Some(20)).unwrap_err(), DeserializationError::Bincode(error) if error.to_string() == "the size limit has been reached" )); let mut expected_res ...
random_line_split
lib.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(missing_docs)] //! The library crate that defines common helper functions that are generally used in //! conjunction with seccompiler-bin. mod common; use bincode::Error as BincodeError; use binc...
} } Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::common::BpfProgram; use std::collections::HashMap; use std::sync::Arc; use std::thread; #[test] fn test_deserialize_binary() { // Malformed bincode binary. { let data = "adassafvc".t...
{ return Err(InstallationError::Prctl(*libc::__errno_location())); }
conditional_block
lib.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![deny(missing_docs)] //! The library crate that defines common helper functions that are generally used in //! conjunction with seccompiler-bin. mod common; use bincode::Error as BincodeError; use binc...
let bpf_prog = sock_fprog { len: bpf_filter.len() as u16, filter: bpf_filter.as_ptr(), }; let bpf_prog_ptr = &bpf_prog as *const sock_fprog; { let rc = libc::prctl( libc::PR_SET_SECCOMP, libc::SECCOMP_MODE_FILTER, ...
{ // If the program is empty, don't install the filter. if bpf_filter.is_empty() { return Ok(()); } // If the program length is greater than the limit allowed by the kernel, // fail quickly. Otherwise, `prctl` will give a more cryptic error code. if bpf_filter.len() > BPF_MAX_LEN { ...
identifier_body
2_13.rs
extern crate cryptopal; extern crate hex; use std::iter::repeat; use std::str; use cryptopal::oracle::{Oracle, ProfileOracle}; use cryptopal::pkcs; use cryptopal::util; fn string_of_n(n: usize) -> String { repeat("B").take(n).collect::<String>() } fn main() { let oracle = ProfileOracle::new(); let bloc...
// create our composite ciphertext using the first two blocks of the C1 // ciphertext (designed to place the role= at the block edge) // append the C2 ciphertext block which contains the isolated `admin` literal let mut f: Vec<u8> = Vec::new(); c1_chunked[0..2].iter().for_each(|c| f.extend_from_sli...
p2.extend_from_slice(string_of_n(padding_to_block_edge).as_bytes()); p2.extend(pkcs::pad("admin".as_bytes(), block_size)); let c2 = oracle.encrypt(&p2); let c2_chunked: Vec<&[u8]> = c2.chunks(block_size).collect();
random_line_split
2_13.rs
extern crate cryptopal; extern crate hex; use std::iter::repeat; use std::str; use cryptopal::oracle::{Oracle, ProfileOracle}; use cryptopal::pkcs; use cryptopal::util; fn string_of_n(n: usize) -> String { repeat("B").take(n).collect::<String>() } fn
() { let oracle = ProfileOracle::new(); let block_size = util::calculate_oracle_block_size(&oracle).expect("bad oracle"); let payload_length = util::calculate_total_payload_length(&oracle).expect("bad payload"); let prefix_length = util::calculate_prefix_length(&oracle).expect("bad oracle"); let su...
main
identifier_name
2_13.rs
extern crate cryptopal; extern crate hex; use std::iter::repeat; use std::str; use cryptopal::oracle::{Oracle, ProfileOracle}; use cryptopal::pkcs; use cryptopal::util; fn string_of_n(n: usize) -> String
fn main() { let oracle = ProfileOracle::new(); let block_size = util::calculate_oracle_block_size(&oracle).expect("bad oracle"); let payload_length = util::calculate_total_payload_length(&oracle).expect("bad payload"); let prefix_length = util::calculate_prefix_length(&oracle).expect("bad oracle"); ...
{ repeat("B").take(n).collect::<String>() }
identifier_body
scif.rs
//! formatter for %e %E scientific notation subs use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; pub struct Scif { as_num: f64, } impl Scif { pub fn new() -> S...
fn primitive_to_str(&self, prim: &FormatPrimitive, field: FormatField) -> String { primitive_to_str_common(prim, &field) } }
{ let second_field = field.second_field.unwrap_or(6) + 1; let analysis = FloatAnalysis::analyze( str_in, inprefix, Some(second_field as usize + 1), None, false, ); let f = get_primitive_dec( inprefix, &st...
identifier_body
scif.rs
//! formatter for %e %E scientific notation subs use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; pub struct Scif { as_num: f64, } impl Scif {
impl Formatter for Scif { fn get_primitive( &self, field: &FormatField, inprefix: &InPrefix, str_in: &str, ) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; let analysis = FloatAnalysis::analyze( str_in, ...
pub fn new() -> Scif { Scif { as_num: 0.0 } } }
random_line_split
scif.rs
//! formatter for %e %E scientific notation subs use super::super::format_field::FormatField; use super::super::formatter::{FormatPrimitive, Formatter, InPrefix}; use super::float_common::{get_primitive_dec, primitive_to_str_common, FloatAnalysis}; pub struct Scif { as_num: f64, } impl Scif { pub fn new() -> S...
( &self, field: &FormatField, inprefix: &InPrefix, str_in: &str, ) -> Option<FormatPrimitive> { let second_field = field.second_field.unwrap_or(6) + 1; let analysis = FloatAnalysis::analyze( str_in, inprefix, Some(second_field as us...
get_primitive
identifier_name
const-vecs-and-slices.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. static x : [int; 4]...
//
random_line_split
const-vecs-and-slices.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 ...
{ println!("{}", x[1]); println!("{}", y[1]); println!("{}", z[1]); println!("{}", zz[1]); assert_eq!(x[1], 2); assert_eq!(x[3], 4); assert_eq!(x[3], y[3]); assert_eq!(z[1], 2); assert_eq!(z[3], 4); assert_eq!(z[3], y[3]); assert_eq!(zz[1], 2); assert_eq!(zz[3], 4); a...
identifier_body
const-vecs-and-slices.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 ...
() { println!("{}", x[1]); println!("{}", y[1]); println!("{}", z[1]); println!("{}", zz[1]); assert_eq!(x[1], 2); assert_eq!(x[3], 4); assert_eq!(x[3], y[3]); assert_eq!(z[1], 2); assert_eq!(z[3], 4); assert_eq!(z[3], y[3]); assert_eq!(zz[1], 2); assert_eq!(zz[3], 4); ...
main
identifier_name
lib.rs
//! # Test CLI Applications //! //! This crate's goal is to provide you some very easy tools to test your CLI //! applications. It can currently execute child processes and validate their //! exit status as well as stdout and stderr output against your assertions. //! //! Include the crate like //! //! ```rust //! #[ma...
mod assert; mod diff; mod output; pub use assert::Assert; pub use assert::OutputAssertionBuilder; /// Environment is a re-export of the Environment crate /// /// It allow you to define/override environment variables for one or more assertions. pub use environment::Environment;
mod macros; pub use macros::flatten_escaped_string;
random_line_split
main.rs
use byteorder::{BigEndian, ByteOrder}; fn main() { // Exercise external crate, printing to stdout. let buf = &[1,2,3,4]; let n = <BigEndian as ByteOrder>::read_u32(buf); assert_eq!(n, 0x01020304); println!("{:#010x}", n); // Access program arguments, printing to stderr. for arg in std::env...
() { let mut rng = rand::rngs::StdRng::seed_from_u64(0xcafebeef); let x: u32 = rng.gen(); let y: usize = rng.gen(); let z: u128 = rng.gen(); assert_ne!(x as usize, y); assert_ne!(y as u128, z); } }
rng
identifier_name
main.rs
use byteorder::{BigEndian, ByteOrder}; fn main() { // Exercise external crate, printing to stdout. let buf = &[1,2,3,4]; let n = <BigEndian as ByteOrder>::read_u32(buf); assert_eq!(n, 0x01020304); println!("{:#010x}", n);
eprintln!("{}", arg); } } #[cfg(test)] mod test { use rand::{Rng, SeedableRng}; // Make sure in-crate tests with dev-dependencies work #[test] fn rng() { let mut rng = rand::rngs::StdRng::seed_from_u64(0xcafebeef); let x: u32 = rng.gen(); let y: usize = rng.gen(); ...
// Access program arguments, printing to stderr. for arg in std::env::args() {
random_line_split
main.rs
use byteorder::{BigEndian, ByteOrder}; fn main() { // Exercise external crate, printing to stdout. let buf = &[1,2,3,4]; let n = <BigEndian as ByteOrder>::read_u32(buf); assert_eq!(n, 0x01020304); println!("{:#010x}", n); // Access program arguments, printing to stderr. for arg in std::env...
}
{ let mut rng = rand::rngs::StdRng::seed_from_u64(0xcafebeef); let x: u32 = rng.gen(); let y: usize = rng.gen(); let z: u128 = rng.gen(); assert_ne!(x as usize, y); assert_ne!(y as u128, z); }
identifier_body
executor.rs
use crossbeam::channel; use scoped_pool::{Pool, ThreadConfig}; use Result; /// Search executor whether search request are single thread or multithread. /// /// We don't expose Rayon thread pool directly here for several reasons. /// /// First dependency hell. It is not a good idea to expose the /// API of a dependency...
} #[cfg(test)] mod tests { use super::Executor; #[test] #[should_panic(expected = "panic should propagate")] fn test_panic_propagates_single_thread() { let _result: Vec<usize> = Executor::single_thread() .map( |_| { panic!("panic should propagate...
random_line_split
executor.rs
use crossbeam::channel; use scoped_pool::{Pool, ThreadConfig}; use Result; /// Search executor whether search request are single thread or multithread. /// /// We don't expose Rayon thread pool directly here for several reasons. /// /// First dependency hell. It is not a good idea to expose the /// API of a dependency...
// This ends the scope of fruit_sender. // This is important as it makes it possible for the fruit_receiver iteration to // terminate. }; // This is lame, but safe. let mut results_with_position = Vec::with_capac...
{ match self { Executor::SingleThread => args.map(f).collect::<Result<_>>(), Executor::ThreadPool(pool) => { let args_with_indices: Vec<(usize, A)> = args.enumerate().collect(); let num_fruits = args_with_indices.len(); let fruit_receiver =...
identifier_body
executor.rs
use crossbeam::channel; use scoped_pool::{Pool, ThreadConfig}; use Result; /// Search executor whether search request are single thread or multithread. /// /// We don't expose Rayon thread pool directly here for several reasons. /// /// First dependency hell. It is not a good idea to expose the /// API of a dependency...
{ SingleThread, ThreadPool(Pool), } impl Executor { /// Creates an Executor that performs all task in the caller thread. pub fn single_thread() -> Executor { Executor::SingleThread } // Creates an Executor that dispatches the tasks in a thread pool. pub fn multi_thread(num_threads...
Executor
identifier_name
lib.rs
#![deny(broken_intra_doc_links)] //! Implementation of marshaller for rust-protobuf parameter types. use bytes::Bytes; use grpc::marshall::Marshaller; use protobuf::CodedInputStream; use protobuf::Message; pub struct MarshallerProtobuf; impl<M: Message> Marshaller<M> for MarshallerProtobuf { fn write_size_est...
fn write(&self, m: &M, _size_esimate: u32, out: &mut Vec<u8>) -> grpc::Result<()> { m.write_to_vec(out) .map_err(|e| grpc::Error::Marshaller(Box::new(e))) } fn read(&self, buf: Bytes) -> grpc::Result<M> { // TODO: make protobuf simple let mut is = CodedInputStream::from...
{ // TODO: implement it Ok(0) }
identifier_body
lib.rs
#![deny(broken_intra_doc_links)] //! Implementation of marshaller for rust-protobuf parameter types. use bytes::Bytes; use grpc::marshall::Marshaller; use protobuf::CodedInputStream; use protobuf::Message; pub struct
; impl<M: Message> Marshaller<M> for MarshallerProtobuf { fn write_size_estimate(&self, _m: &M) -> grpc::Result<u32> { // TODO: implement it Ok(0) } fn write(&self, m: &M, _size_esimate: u32, out: &mut Vec<u8>) -> grpc::Result<()> { m.write_to_vec(out) .map_err(|e| grpc:...
MarshallerProtobuf
identifier_name
lib.rs
#![deny(broken_intra_doc_links)] //! Implementation of marshaller for rust-protobuf parameter types. use bytes::Bytes; use grpc::marshall::Marshaller;
use protobuf::CodedInputStream; use protobuf::Message; pub struct MarshallerProtobuf; impl<M: Message> Marshaller<M> for MarshallerProtobuf { fn write_size_estimate(&self, _m: &M) -> grpc::Result<u32> { // TODO: implement it Ok(0) } fn write(&self, m: &M, _size_esimate: u32, out: &mut Ve...
random_line_split
errors.rs
use std::error; use std::fmt; use std::io; use parsed_class::FieldRef; #[derive(Debug)] pub enum ClassLoadingError { NoClassDefFound(Result<String, io::Error>), ClassFormatError(String), UnsupportedClassVersion, NoSuchFieldError(FieldRef), #[allow(dead_code)] IncompatibleClassChange, #[allo...
}
match *self { ClassLoadingError::NoClassDefFound(ref err) => err.as_ref().err().map(|e| e as &error::Error), _ => None, } }
random_line_split
errors.rs
use std::error; use std::fmt; use std::io; use parsed_class::FieldRef; #[derive(Debug)] pub enum ClassLoadingError { NoClassDefFound(Result<String, io::Error>), ClassFormatError(String), UnsupportedClassVersion, NoSuchFieldError(FieldRef), #[allow(dead_code)] IncompatibleClassChange, #[allo...
fn cause(&self) -> Option<&error::Error> { match *self { ClassLoadingError::NoClassDefFound(ref err) => err.as_ref().err().map(|e| e as &error::Error), _ => None, } } }
{ match *self { ClassLoadingError::NoClassDefFound(..) => "NoClassDefFound", ClassLoadingError::ClassFormatError(..) => "ClassFormatError", ClassLoadingError::NoSuchFieldError(..) => "NoSuchFieldError", ClassLoadingError::UnsupportedClassVersion => "UnsupportedCla...
identifier_body
errors.rs
use std::error; use std::fmt; use std::io; use parsed_class::FieldRef; #[derive(Debug)] pub enum
{ NoClassDefFound(Result<String, io::Error>), ClassFormatError(String), UnsupportedClassVersion, NoSuchFieldError(FieldRef), #[allow(dead_code)] IncompatibleClassChange, #[allow(dead_code)] ClassCircularity, } impl fmt::Display for ClassLoadingError { fn fmt(&self, f: &mut fmt::For...
ClassLoadingError
identifier_name
issue-13482.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 ...
{ let x = [1,2]; let y = match x { [] => None, //~^ ERROR mismatched types //~| expected `[_; 2]` //~| found `[_; 0]` //~| expected array with a fixed size of 2 elements [a,_] => Some(a) }; }
identifier_body
issue-13482.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 ...
let y = match x { [] => None, //~^ ERROR mismatched types //~| expected `[_; 2]` //~| found `[_; 0]` //~| expected array with a fixed size of 2 elements [a,_] => Some(a) }; }
#![feature(slice_patterns)] fn main() { let x = [1,2];
random_line_split
issue-13482.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 ...
() { let x = [1,2]; let y = match x { [] => None, //~^ ERROR mismatched types //~| expected `[_; 2]` //~| found `[_; 0]` //~| expected array with a fixed size of 2 elements [a,_] => Some(a) }; }
main
identifier_name
main.rs
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use std::collections::HashMap; const INPUT: &'static str = "ihaygndm"; fn get_hash(n: i32, sieve: &mut HashMap<i32, String>) -> String { if!sieve.contains_key(&n) { let mut hasher = Md5::new(); hasher.input_str(INPUT); ...
loop { let cur = get_hash2(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { let opt = get_hash2(n + i, &mut sieve); if opt.contains(&search)...
let mut found = 0; let mut sieve = HashMap::new();
random_line_split
main.rs
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use std::collections::HashMap; const INPUT: &'static str = "ihaygndm"; fn get_hash(n: i32, sieve: &mut HashMap<i32, String>) -> String { if!sieve.contains_key(&n) { let mut hasher = Md5::new(); hasher.input_str(INPUT); ...
fn part1() { let mut n = 0; let mut found = 0; let mut sieve = HashMap::new(); loop { let cur = get_hash(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { ...
{ if !sieve.contains_key(&n) { let mut cur = String::from(INPUT); cur += &n.to_string(); for _ in 0..2017 { let mut hasher = Md5::new(); hasher.input_str(&cur); cur = String::from(hasher.result_str()); } sieve.insert(n, cur); } ret...
identifier_body
main.rs
extern crate crypto; use crypto::md5::Md5; use crypto::digest::Digest; use std::collections::HashMap; const INPUT: &'static str = "ihaygndm"; fn get_hash(n: i32, sieve: &mut HashMap<i32, String>) -> String { if!sieve.contains_key(&n) { let mut hasher = Md5::new(); hasher.input_str(INPUT); ...
() { let mut n = 0; let mut found = 0; let mut sieve = HashMap::new(); loop { let cur = get_hash2(n, &mut sieve); match contains_3(&cur) { Some(c) => { let search: String = (0..5).map(|_| c).collect(); for i in 1..1001 { l...
part2
identifier_name
font.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 app_units::Au; use euclid::{Point2D, Rect, Size2D}; use font_template::FontTemplateDescriptor; use ordered_flo...
let end_time = time::precise_time_ns(); TEXT_SHAPING_PERFORMANCE_COUNTER.fetch_add((end_time - start_time) as usize, Ordering::Relaxed); Arc::new(glyphs) }).clone(); self.shaper = shaper; result } ...
{ debug!("shape_text: Using Harfbuzz."); if shaper.is_none() { shaper = Some(Shaper::new(this)); } shaper.as_ref().unwrap().shape_text(text, options, &mut glyphs); }
conditional_block
font.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 app_units::Au; use euclid::{Point2D, Rect, Size2D}; use font_template::FontTemplateDescriptor; use ordered_flo...
use webrender_api; macro_rules! ot_tag { ($t1:expr, $t2:expr, $t3:expr, $t4:expr) => ( (($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32) ); } pub const GPOS: u32 = ot_tag!('G', 'P', 'O', 'S'); pub const GSUB: u32 = ot_tag!('G', 'S', 'U', 'B'); pub const KERN: u32 = ot_ta...
use text::shaping::ShaperMethods; use time; use unicode_script::Script;
random_line_split
font.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 app_units::Au; use euclid::{Point2D, Rect, Size2D}; use font_template::FontTemplateDescriptor; use ordered_flo...
{ pub fonts: SmallVec<[Rc<RefCell<Font>>; 8]>, } impl FontGroup { pub fn new(fonts: SmallVec<[Rc<RefCell<Font>>; 8]>) -> FontGroup { FontGroup { fonts: fonts, } } } pub struct RunMetrics { // may be negative due to negative width (i.e., kerning of '.' in 'P.T.') pub ad...
FontGroup
identifier_name
lorenz96.rs
//! Lorenz 96 model //! https://en.wikipedia.org/wiki/Lorenz_96_model use crate::traits::*; use ndarray::*; #[derive(Clone, Copy, Debug)] pub struct Lorenz96 { pub f: f64, pub n: usize, } impl Default for Lorenz96 { fn default() -> Self { Lorenz96 { f: 8.0, n: 40 } } } impl ModelSpec for Lor...
<'a, S>(&mut self, v: &'a mut ArrayBase<S, Ix1>) -> &'a mut ArrayBase<S, Ix1> where S: DataMut<Elem = f64>, { let n = v.len(); let v0 = v.to_owned(); for i in 0..n { let p1 = (i + 1) % n; let m1 = (i + n - 1) % n; let m2 = (i + n - 2) % n; ...
rhs
identifier_name
lorenz96.rs
//! Lorenz 96 model //! https://en.wikipedia.org/wiki/Lorenz_96_model use crate::traits::*; use ndarray::*; #[derive(Clone, Copy, Debug)] pub struct Lorenz96 { pub f: f64, pub n: usize, } impl Default for Lorenz96 { fn default() -> Self { Lorenz96 { f: 8.0, n: 40 } }
impl ModelSpec for Lorenz96 { type Scalar = f64; type Dim = Ix1; fn model_size(&self) -> usize { self.n } } impl Explicit for Lorenz96 { fn rhs<'a, S>(&mut self, v: &'a mut ArrayBase<S, Ix1>) -> &'a mut ArrayBase<S, Ix1> where S: DataMut<Elem = f64>, { let n = v.len...
}
random_line_split
lorenz96.rs
//! Lorenz 96 model //! https://en.wikipedia.org/wiki/Lorenz_96_model use crate::traits::*; use ndarray::*; #[derive(Clone, Copy, Debug)] pub struct Lorenz96 { pub f: f64, pub n: usize, } impl Default for Lorenz96 { fn default() -> Self
} impl ModelSpec for Lorenz96 { type Scalar = f64; type Dim = Ix1; fn model_size(&self) -> usize { self.n } } impl Explicit for Lorenz96 { fn rhs<'a, S>(&mut self, v: &'a mut ArrayBase<S, Ix1>) -> &'a mut ArrayBase<S, Ix1> where S: DataMut<Elem = f64>, { let n = v...
{ Lorenz96 { f: 8.0, n: 40 } }
identifier_body
coulomb.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use toml::Value; use lumol_core::energy::{CoulombicPotential, Ewald, SharedEwald, Wolf}; use lumol_core::System; use log::{info, warn}; use super::read_restriction; use crate::{InteractionsInput, Error, FromToml, ...
self, system: &mut System) -> Result<(), Error> { let coulomb = match self.config.get("coulomb") { Some(coulomb) => coulomb, None => return Ok(()), }; let coulomb = coulomb.as_table().ok_or(Error::from("the 'coulomb' section must be a table"))?; let solvers = co...
ad_coulomb(&
identifier_name
coulomb.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use toml::Value; use lumol_core::energy::{CoulombicPotential, Ewald, SharedEwald, Wolf}; use lumol_core::System; use log::{info, warn}; use super::read_restriction; use crate::{InteractionsInput, Error, FromToml, ...
let ewald = Ewald::from_toml(table, &system)?; Box::new(SharedEwald::new(ewald)) } other => return Err(Error::from(format!("unknown coulomb solver '{}'", other))), }; if let Some(restriction) = read_restriction(coulomb)? { ...
let coulomb = match self.config.get("coulomb") { Some(coulomb) => coulomb, None => return Ok(()), }; let coulomb = coulomb.as_table().ok_or(Error::from("the 'coulomb' section must be a table"))?; let solvers = coulomb.keys().cloned().filter(|key| key != "restric...
identifier_body
coulomb.rs
// Lumol, an extensible molecular simulation engine // Copyright (C) Lumol's contributors — BSD license use toml::Value; use lumol_core::energy::{CoulombicPotential, Ewald, SharedEwald, Wolf}; use lumol_core::System; use log::{info, warn}; use super::read_restriction; use crate::{InteractionsInput, Error, FromToml, ...
let mut total_charge = 0.0; for (name, charge) in charges.iter() { let charge = match *charge { Value::Integer(val) => val as f64, Value::Float(val) => val, _ => { return Err(Error::from("charges must be numbers")); ...
random_line_split
next_back.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> {...
() { let mut a: A<T> = A { begin: 0, end: 10 }; let mut iter: &mut I = &mut a; for x in 0..10 { let y: Option<T> = iter.next_back(); match y { Some(v) => { assert_eq!(v, 9 - x); } None => { assert!(false); } } } assert_eq!(iter.next(), None::<<I as Iterator>::Item>);; } }
next_back_test1
identifier_name
next_back.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> {...
}
{ let mut a: A<T> = A { begin: 0, end: 10 }; let mut iter: &mut I = &mut a; for x in 0..10 { let y: Option<T> = iter.next_back(); match y { Some(v) => { assert_eq!(v, 9 - x); } None => { assert!(false); } } } assert_eq!(iter.next(), None::<<I as Iterator>::Item>);; }
identifier_body
next_back.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::DoubleEndedIterator; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> {...
}
} } assert_eq!(iter.next(), None::<<I as Iterator>::Item>);; }
random_line_split
canvasgradient.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 canvas::canvas_paint_task::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, R...
self.stops.borrow_mut().push(CanvasGradientStop { offset: (*offset) as f64, color: parse_color(&color).unwrap_or(default_black), }); } } pub trait ToFillOrStrokeStyle { fn to_fill_or_stroke_style(&self) -> FillOrStrokeStyle; } impl<'a> ToFillOrStrokeStyle for JSRef<'a, ...
random_line_split
canvasgradient.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 canvas::canvas_paint_task::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, R...
, CanvasGradientStyle::Radial(ref gradient) => { FillOrStrokeStyle::RadialGradient( RadialGradientStyle::new(gradient.x0, gradient.y0, gradient.r0, gradient.x1, gradient.y1, gradient.r1, ...
{ FillOrStrokeStyle::LinearGradient( LinearGradientStyle::new(gradient.x0, gradient.y0, gradient.x1, gradient.y1, gradient_stops)) }
conditional_block
canvasgradient.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 canvas::canvas_paint_task::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, R...
(global: GlobalRef, style: CanvasGradientStyle) -> Temporary<CanvasGradient> { reflect_dom_object(box CanvasGradient::new_inherited(style), global, CanvasGradientBinding::Wrap) } } impl<'a> CanvasGradientMethods for JSRef<'a, CanvasGradient> { // https://html.spec.whatwg.org/...
new
identifier_name
viewport.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 app_units::Au; use style::properties::PropertyDeclaration; use style::properties::longhands::border_top_width;...
border_top_width::SpecifiedValue::from_length( Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(Au(100).to_f32_px()))) ) ); assert!(!pabs.has_viewport_percentage()); }
) ); assert!(pvw.has_viewport_percentage()); let pabs = PropertyDeclaration::BorderTopWidth(
random_line_split
viewport.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 app_units::Au; use style::properties::PropertyDeclaration; use style::properties::longhands::border_top_width;...
{ //TODO: test all specified value with a HasViewportPercentage impl let pvw = PropertyDeclaration::BorderTopWidth( border_top_width::SpecifiedValue::from_length( Length::NoCalc(NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vw(100.))) ) ); assert!(pvw.has_viewpor...
identifier_body
viewport.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 app_units::Au; use style::properties::PropertyDeclaration; use style::properties::longhands::border_top_width;...
() { //TODO: test all specified value with a HasViewportPercentage impl let pvw = PropertyDeclaration::BorderTopWidth( border_top_width::SpecifiedValue::from_length( Length::NoCalc(NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vw(100.))) ) ); assert!(pvw.has_view...
has_viewport_percentage_for_specified_value
identifier_name
zero-size-array-align.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { #[inline] pub const fn new() -> Self { __IncompleteArrayFie...
} #[repr(C)] #[derive(Debug, Default)] pub struct dm_deps { pub count: ::std::os::raw::c_uint, pub filler: ::std::os::raw::c_uint, pub device: __IncompleteArrayField<::std::os::raw::c_ulonglong>, } #[test] fn bindgen_test_layout_dm_deps() { assert_eq!( ::std::mem::size_of::<dm_deps>(), ...
{ fmt.write_str("__IncompleteArrayField") }
identifier_body
zero-size-array-align.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { #[inline] pub const fn new() -> Self { __IncompleteArrayFie...
(&mut self) -> *mut T { self as *mut _ as *mut T } #[inline] pub unsafe fn as_slice(&self, len: usize) -> &[T] { ::std::slice::from_raw_parts(self.as_ptr(), len) } #[inline] pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { ::std::slice::from_raw_parts_mut(s...
as_mut_ptr
identifier_name
zero-size-array-align.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]); impl<T> __IncompleteArrayField<T> { #[inline] pub const fn new() -> Self { __IncompleteArrayFie...
); assert_eq!( ::std::mem::align_of::<dm_deps>(), 8usize, concat!("Alignment of ", stringify!(dm_deps)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<dm_deps>())).count as *const _ as usize }, 0usize, concat!( "Offset of fi...
random_line_split
issue-2834.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 ...
pub fn main() { //os::getenv("FOO"); rendezvous(); }
random_line_split
issue-2834.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 ...
pub fn main() { //os::getenv("FOO"); rendezvous(); }
{ let (s, c) = streamp::init(); let streams: ~[streamp::client::open<int>] = ~[c]; error!("%?", streams[0]); }
identifier_body