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
lr.template.rs
#![allow(dead_code)] #![allow(unused_mut)] #![allow(unreachable_code)] extern crate onig; #[macro_use] extern crate lazy_static; use onig::{Regex, Syntax, RegexOptions}; use std::collections::HashMap; /** * Stack value. */ enum SV { Undefined, {{{SV_ENUM}}} } /** * Lex rules. */ static LEX_RULES: {{{LE...
{{{PRODUCTION_HANDLERS}}} }
{ {{{ON_PARSE_ERROR_CALL}}} }
identifier_body
lr.template.rs
#![allow(dead_code)] #![allow(unused_mut)] #![allow(unreachable_code)] extern crate onig; #[macro_use] extern crate lazy_static; use onig::{Regex, Syntax, RegexOptions}; use std::collections::HashMap; /** * Stack value. */ enum SV { Undefined, {{{SV_ENUM}}} } /** * Lex rules. */ static LEX_RULES: {{{LE...
while rhs_length > 0 { self.states_stack.pop(); rhs_length = rhs_length - 1; } // Call the handler, push result onto the stack. let result_value = self.handlers[production_number](self); ...
let mut rhs_length = production[1];
random_line_split
registrar.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...
impl Visitor<()> for MacroRegistrarContext { fn visit_item(&mut self, item: &ast::Item, _: ()) { match item.node { ast::ItemFn(..) => { if attr::contains_name(item.attrs.as_slice(), "macro_registrar") { self.registrars.pu...
registrars: Vec<(ast::NodeId, Span)> , }
random_line_split
registrar.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...
(diagnostic: &diagnostic::SpanHandler, krate: &ast::Crate) -> Option<ast::DefId> { let mut ctx = MacroRegistrarContext { registrars: Vec::new() }; visit::walk_crate(&mut ctx, krate, ()); match ctx.registrars.len() { 0 => None, 1 => { let (node_id, _) ...
find_macro_registrar
identifier_name
registrar.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...
} visit::walk_item(self, item, ()); } } pub fn find_macro_registrar(diagnostic: &diagnostic::SpanHandler, krate: &ast::Crate) -> Option<ast::DefId> { let mut ctx = MacroRegistrarContext { registrars: Vec::new() }; visit::walk_crate(&mut ctx, krate, ()); ma...
{}
conditional_block
text_documents.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! Utilities related to LSP text document syncing use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState}; use l...
.starts_with(lsp_state.root_dir().to_string_lossy().as_ref()) { return Ok(()); } lsp_state.document_closed(&uri) } pub fn on_did_change_text_document( lsp_state: &impl GlobalState, params: <DidChangeTextDocument as Notification>::Params, ) -> LSPRuntimeResult<()> { let DidChange...
let uri = params.text_document.uri; if !uri .path()
random_line_split
text_documents.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! Utilities related to LSP text document syncing use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState}; use l...
#[allow(clippy::unnecessary_wraps)] pub fn on_cancel( _lsp_state: &impl GlobalState, _params: <Cancel as Notification>::Params, ) -> LSPRuntimeResult<()> { Ok(()) }
{ Ok(()) }
identifier_body
text_documents.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! Utilities related to LSP text document syncing use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState}; use l...
lsp_state.document_opened(&uri, &text) } #[allow(clippy::unnecessary_wraps)] pub fn on_did_close_text_document( lsp_state: &impl GlobalState, params: <DidCloseTextDocument as Notification>::Params, ) -> LSPRuntimeResult<()> { let uri = params.text_document.uri; if!uri .path() .start...
{ return Ok(()); }
conditional_block
text_documents.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ //! Utilities related to LSP text document syncing use crate::{lsp_runtime_error::LSPRuntimeResult, server::GlobalState}; use l...
( lsp_state: &impl GlobalState, params: <DidOpenTextDocument as Notification>::Params, ) -> LSPRuntimeResult<()> { let DidOpenTextDocumentParams { text_document } = params; let TextDocumentItem { text, uri,.. } = text_document; if!uri .path() .starts_with(lsp_state.root_dir().to_string...
on_did_open_text_document
identifier_name
vpcmpistri.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn vpcmpistri_1() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(D...
{ run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Eight, 1057295119, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadc...
identifier_body
vpcmpistri.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn vpcmpistri_1() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(D...
() { run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledDisplaced(RBX, Eight, 1057295119, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, bro...
vpcmpistri_4
identifier_name
vpcmpistri.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*;
run_test(&Instruction { mnemonic: Mnemonic::VPCMPISTRI, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM6)), operand3: Some(Literal8(114)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 121, 99, 214, 114], OperandSize::Dword) } fn ...
use ::Reg::*; use ::RegScale::*; fn vpcmpistri_1() {
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // For simd (currently x86_64/aarch64) #![cfg_attr(any(target_os = "linux", target_os = "android", target_os = "wi...
// Platforms that use Freetype/Fontconfig library dependencies #[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))] extern crate fontconfig; #[cfg(any(target_os = "linux", target_os = "android", target_os = "windows"))] extern crate freetype; extern crate gfx_traits; // Eventually we would l...
extern crate euclid; extern crate fnv;
random_line_split
unparse.rs
use crate::{ ast::{Ast, AstContents, AstContents::*}, grammar::{ FormPat::{self, *}, SynEnv, }, name::*, util::mbe::EnvMBE, }; fn node_names_mentioned(pat: &FormPat) -> Vec<Name> { match *pat { Named(n, ref body) => { let mut res = node_names_mentioned(&*body...
} first = false; res.push_str(&unparse_mbe(&*sub_pat, actl, &marched_ctxt, s)); } res } (&Scope(ref form, _), &Node(ref form_actual, ref body, _)) => { if form == form_actual { unparse_mbe(&*form.grammar,...
if !first { res.push(' ');
random_line_split
unparse.rs
use crate::{ ast::{Ast, AstContents, AstContents::*}, grammar::{ FormPat::{self, *}, SynEnv, }, name::*, util::mbe::EnvMBE, }; fn node_names_mentioned(pat: &FormPat) -> Vec<Name> { match *pat { Named(n, ref body) => { let mut res = node_names_mentioned(&*body...
// TODO: this really ought to notice when `actl` is ill-formed for `pat`. match (pat, actl) { (&Named(name, ref body), _) => { // TODO: why does the `unwrap_or` case happen once after each variable is printed? unparse_mbe(&*body, context.get_leaf(name).unwrap_or(&ast!((at ""))).c...
{ // HACK: handle underdetermined forms let undet = crate::ty_compare::underdetermined_form.with(|u| u.clone()); match actl { Node(form, body, _) if form == &undet => { return crate::ty_compare::unification.with(|unif| { let var = body.get_leaf_or_panic(&n("id")).to_name(...
identifier_body
unparse.rs
use crate::{ ast::{Ast, AstContents, AstContents::*}, grammar::{ FormPat::{self, *}, SynEnv, }, name::*, util::mbe::EnvMBE, }; fn
(pat: &FormPat) -> Vec<Name> { match *pat { Named(n, ref body) => { let mut res = node_names_mentioned(&*body); res.push(n); res } Scope(_, _) => vec![], Pick(_, _) => vec![], Star(ref body) | Plus(ref body) | NameImport(ref...
node_names_mentioned
identifier_name
unparse.rs
use crate::{ ast::{Ast, AstContents, AstContents::*}, grammar::{ FormPat::{self, *}, SynEnv, }, name::*, util::mbe::EnvMBE, }; fn node_names_mentioned(pat: &FormPat) -> Vec<Name> { match *pat { Named(n, ref body) => { let mut res = node_names_mentioned(&*body...
let sub_res = unparse_mbe(&*sub_pat, actl, context, s); if sub_res!= "" { return sub_res; } // HACK: should use `Option` } // HACK: certain forms don't live in the syntax environment, // but "belong" under an `Alt`...
any_scopes = true; continue; }
conditional_block
flow_control.rs
#![allow(dead_code, unreachable_code, unused_variables)] pub fn flow_control() { println!("***Flow Control***"); if_else(); loops(); whiles(); for_ranges(); matching(); if_let(); while_let(); println!(""); } fn if_else() { let n = 5; if n < 0 { print!("{} is nega...
match reference { &val => println!("Got by destructuring: {:?}", val), } // to avoid the '&', dereference before matching match *reference { val => println!("Got by dereferencing: {:?}", val), } // same as &3 let ref is_a_ref = 3; let value = 5; let mut mut_value...
let reference = &4;
random_line_split
flow_control.rs
#![allow(dead_code, unreachable_code, unused_variables)] pub fn flow_control() { println!("***Flow Control***"); if_else(); loops(); whiles(); for_ranges(); matching(); if_let(); while_let(); println!(""); } fn if_else() { let n = 5; if n < 0 { print!("{} is nega...
{ 15 }
identifier_body
flow_control.rs
#![allow(dead_code, unreachable_code, unused_variables)] pub fn flow_control() { println!("***Flow Control***"); if_else(); loops(); whiles(); for_ranges(); matching(); if_let(); while_let(); println!(""); } fn if_else() { let n = 5; if n < 0 { print!("{} is nega...
() -> u32 { 15 }
age
identifier_name
context.rs
//! Provides a Rust wrapper around Cuda's context. use device::{IDevice, DeviceType, IDeviceSyncOut}; use device::Error as DeviceError; use super::api::DriverFFI; use super::{Driver, DriverError, Device}; use super::memory::*; #[cfg(feature = "native")] use frameworks::native::flatbox::FlatBox; use memory::MemoryType;...
id: Rc::new(id as isize), devices: devices } } /// Returns the id as isize. pub fn id(&self) -> isize { *self.id } /// Returns the id as its C type. pub fn id_c(&self) -> DriverFFI::CUcontext { *self.id as DriverFFI::CUcontext } /// Sync...
/// Initializes a new Cuda platform from its C type. pub fn from_c(id: DriverFFI::CUcontext, devices: Vec<Device>) -> Context { Context {
random_line_split
context.rs
//! Provides a Rust wrapper around Cuda's context. use device::{IDevice, DeviceType, IDeviceSyncOut}; use device::Error as DeviceError; use super::api::DriverFFI; use super::{Driver, DriverError, Device}; use super::memory::*; #[cfg(feature = "native")] use frameworks::native::flatbox::FlatBox; use memory::MemoryType;...
(devices: Device) -> Result<Context, DriverError> { Ok( Context::from_c( try!(Driver::create_context(devices.clone())), vec!(devices.clone()) ) ) } /// Initializes a new Cuda platform from its C type. pub fn from_c(id: DriverFFI::CUcon...
new
identifier_name
context.rs
//! Provides a Rust wrapper around Cuda's context. use device::{IDevice, DeviceType, IDeviceSyncOut}; use device::Error as DeviceError; use super::api::DriverFFI; use super::{Driver, DriverError, Device}; use super::memory::*; #[cfg(feature = "native")] use frameworks::native::flatbox::FlatBox; use memory::MemoryType;...
/// Synchronize this Context. pub fn synchronize(&self) -> Result<(), DriverError> { Driver::synchronize_context() } } #[cfg(feature = "native")] impl IDeviceSyncOut<FlatBox> for Context { type M = Memory; fn sync_out(&self, source_data: &Memory, dest_data: &mut FlatBox) -> Result<(), Dev...
{ *self.id as DriverFFI::CUcontext }
identifier_body
macros.rs
//macro_rules! batch { //($name : ident, [ $($parts: ident : $pty: ty),* ], [$($defid : ident : $val : expr),*]) => { //impl<T, V> $name<T, V> //where T: EndOffset, //V:Batch + BatchIterator + Act { //#[inline] //pub fn new($( $parts : $pty ),*) -> $name<T, V> { //$name{ $( $parts: $parts ),*, $($defid : $val),* } //}...
batch!{$name, [$($parts:$pty),*], []} } } macro_rules! act { () => { #[inline] fn act(&mut self) { self.parent.act(); } #[inline] fn done(&mut self) { self.parent.done(); } #[inline] fn send_q(&mut self, port: &Pa...
}; ($name: ident, [ $($parts: ident : $pty: ty),* ]) => {
random_line_split
unify.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
if *a_t == b { return Ok(()); } else { return err(a_is_expected, (*a_t).clone(), b); } } } } } /////////////////////////////////////////////////////////////////////////// // Integral type keys impl UnifyK...
{ /*! * Sets the value of the key `a_id` to `b`. Because * simple keys do not have any subtyping relationships, * if `a_id` already has a value, it must be the same as * `b`. */ let tcx = self.tcx; let table = UnifyKey::unification_table(self); ...
identifier_body
unify.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...
(i: uint) -> ty::FloatVid { ty::FloatVid { index: i } } fn unification_table<'v>(infcx: &'v InferCtxt) -> &'v RefCell<UnificationTable<ty::FloatVid, Option<ast::FloatTy>>> { return &infcx.float_unification_table; } fn tag(_: Option<ty::FloatVid>) -> &'static str { "FloatVid" ...
from_index
identifier_name
unify.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...
b_t: V) -> ures { if a_is_expected { Err(SimplyUnifiable::to_type_err( ty::expected_found {expected: a_t, found: b_t})) } else { Err(SimplyUnifiable::to_type_err( ty::expected_found {expected: b_t, found: a_t})) ...
a_t: V,
random_line_split
borrowck-loan-blocks-move-cc.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 ...
() { }
main
identifier_name
borrowck-loan-blocks-move-cc.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 ...
{ }
identifier_body
borrowck-loan-blocks-move-cc.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
use std::thread::Thread; fn borrow<F>(v: &isize, f: F) where F: FnOnce(&isize) { f(v); } fn box_imm() { let v = box 3; let _w = &v; Thread::spawn(move|| { println!("v={}", *v); //~^ ERROR cannot move `v` into closure }); } fn box_imm_explicit() { let v = box 3; let _w = &...
// <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. #![feature(box_syntax)]
random_line_split
main.rs
#![allow(dead_code)] extern crate libc; extern crate jni; use jni::*; #[test] fn test() { assert!(!mytest().is_err()); } fn
() -> Result<(),jni::Exception> { let opt1 = JavaVMOption::new("-Xcheck:jni"); println!("Opt is {:?}", opt1); let opt2 = JavaVMOption::new("-verbose:jni"); println!("Opt is {:?}", opt2); let args = JavaVMInitArgs::new( jni::JniVersion::JNI_VERSION_1_4, &[/*opt1, JavaVMOption::new("-verbose:jni")*/][..], fa...
mytest
identifier_name
main.rs
#![allow(dead_code)] extern crate libc; extern crate jni; use jni::*; #[test] fn test() { assert!(!mytest().is_err()); } fn mytest() -> Result<(),jni::Exception> { let opt1 = JavaVMOption::new("-Xcheck:jni"); println!("Opt is {:?}", opt1); let opt2 = JavaVMOption::new("-verbose:jni"); println!("Opt is {:?}", o...
fn get_val(&self) -> u64 { self.val } } #[test] fn test() { let parent = Parent::new(1); let child = parent.child(2); let obj1 = child.obj1(3); let obj2 = child.obj2(3); assert!(obj1 == obj2); assert!(obj2 == obj1); let parent2 = Parent::new(1); let child2 = parent2.child(2); let obj12 = child2.obj1(3);...
}
random_line_split
main.rs
#![allow(dead_code)] extern crate libc; extern crate jni; use jni::*; #[test] fn test()
fn mytest() -> Result<(),jni::Exception> { let opt1 = JavaVMOption::new("-Xcheck:jni"); println!("Opt is {:?}", opt1); let opt2 = JavaVMOption::new("-verbose:jni"); println!("Opt is {:?}", opt2); let args = JavaVMInitArgs::new( jni::JniVersion::JNI_VERSION_1_4, &[/*opt1, JavaVMOption::new("-verbose:jni")*/...
{ assert!(!mytest().is_err()); }
identifier_body
animated_properties.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 style::properties::animated_properties::{Animatable, IntermediateRGBA}; fn interpolate_r...
RGBA::new(154, 0, 0, 77)); } #[test] fn test_rgba_color_interepolation_out_of_range_2() { assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.6), RGBA::from_floats(0.0, 0.3, 0.0, 0.4), 1.5), RGBA::new(0, 154, 0, 77)); } #[test] fn test_rgba_...
RGBA::from_floats(0.0, 1.0, 0.0, 0.6), -0.5),
random_line_split
animated_properties.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 style::properties::animated_properties::{Animatable, IntermediateRGBA}; fn
(from: RGBA, to: RGBA, progress: f64) -> RGBA { let from: IntermediateRGBA = from.into(); let to: IntermediateRGBA = to.into(); from.interpolate(&to, progress).unwrap().into() } #[test] fn test_rgba_color_interepolation_preserves_transparent() { assert_eq!(interpolate_rgba(RGBA::transparent(), ...
interpolate_rgba
identifier_name
animated_properties.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 style::properties::animated_properties::{Animatable, IntermediateRGBA}; fn interpolate_r...
#[test] fn test_rgba_color_interepolation_out_of_range_2() { assert_eq!(interpolate_rgba(RGBA::from_floats(1.0, 0.0, 0.0, 0.6), RGBA::from_floats(0.0, 0.3, 0.0, 0.4), 1.5), RGBA::new(0, 154, 0, 77)); } #[test] fn test_rgba_color_interepolation_out_of_range_clamped_1...
{ // Some cubic-bezier functions produce values that are out of range [0, 1]. // Unclamped cases. assert_eq!(interpolate_rgba(RGBA::from_floats(0.3, 0.0, 0.0, 0.4), RGBA::from_floats(0.0, 1.0, 0.0, 0.6), -0.5), RGBA::new(154, 0, 0, 77)); }
identifier_body
multihash.rs
use crate::Error; #[cfg(feature = "alloc")] use alloc::vec::Vec; use core::convert::TryFrom; use core::convert::TryInto; use core::fmt::Debug; #[cfg(feature = "serde-codec")] use serde_big_array::BigArray; use unsigned_varint::encode as varint_encode; #[cfg(feature = "std")] use std::io; #[cfg(not(feature = "std"))...
<R: io::Read>(mut r: R) -> Result<u64, Error> { use unsigned_varint::decode; let mut b = varint_encode::u64_buffer(); for i in 0..b.len() { let n = r.read(&mut (b[i..i + 1]))?; if n == 0 { return Err(Error::Varint(decode::Error::Insufficient)); } else if decode::is_last(b...
read_u64
identifier_name
multihash.rs
use crate::Error; #[cfg(feature = "alloc")] use alloc::vec::Vec; use core::convert::TryFrom; use core::convert::TryInto; use core::fmt::Debug; #[cfg(feature = "serde-codec")] use serde_big_array::BigArray; use unsigned_varint::encode as varint_encode; #[cfg(feature = "std")] use std::io; #[cfg(not(feature = "std"))...
#[test] fn test_eq_sizes() { let mh1 = Multihash::<32>::default(); let mh2 = Multihash::<64>::default(); assert_eq!(mh1, mh2); } }
{ let mh = Multihash::<32>::default(); let bytes = serde_json::to_string(&mh).unwrap(); let mh2: Multihash<32> = serde_json::from_str(&bytes).unwrap(); assert_eq!(mh, mh2); }
identifier_body
multihash.rs
use crate::Error; #[cfg(feature = "alloc")] use alloc::vec::Vec; use core::convert::TryFrom; use core::convert::TryInto; use core::fmt::Debug; #[cfg(feature = "serde-codec")] use serde_big_array::BigArray; use unsigned_varint::encode as varint_encode; #[cfg(feature = "std")] use std::io; #[cfg(not(feature = "std"))...
return Err(Error::InvalidSize(bytes.len().try_into().expect( "Currently the maximum size is 255, therefore always fits into usize", ))); } Ok(result) } /// Writes a multihash to a byte stream. pub fn write<W: io::Write>(&self, w: W) -> Result<(), Err...
random_line_split
multihash.rs
use crate::Error; #[cfg(feature = "alloc")] use alloc::vec::Vec; use core::convert::TryFrom; use core::convert::TryInto; use core::fmt::Debug; #[cfg(feature = "serde-codec")] use serde_big_array::BigArray; use unsigned_varint::encode as varint_encode; #[cfg(feature = "std")] use std::io; #[cfg(not(feature = "std"))...
Ok(result) } /// Writes a multihash to a byte stream. pub fn write<W: io::Write>(&self, w: W) -> Result<(), Error> { write_multihash(w, self.code(), self.size(), self.digest()) } #[cfg(feature = "alloc")] /// Returns the bytes of a multihash. pub fn to_bytes(&self) -> Vec...
{ return Err(Error::InvalidSize(bytes.len().try_into().expect( "Currently the maximum size is 255, therefore always fits into usize", ))); }
conditional_block
clear_bits_geq.rs
use word::{Word, ToWord, UnsignedWord}; /// Clears all bits of `x` at position >= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Intrinsics: /// - BMI 2.0: bzhi. /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// assert_eq!(0b1111_0010u8.clear_bits_geq(5u8), 0b0001_0010u8); /// assert_...
impl<T: Word> ClearBitsGeq for T { #[inline] fn clear_bits_geq<U: UnsignedWord>(self, n: U) -> Self { clear_bits_geq(self, n) } }
random_line_split
clear_bits_geq.rs
use word::{Word, ToWord, UnsignedWord}; /// Clears all bits of `x` at position >= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Intrinsics: /// - BMI 2.0: bzhi. /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// assert_eq!(0b1111_0010u8.clear_bits_geq(5u8), 0b0001_0010u8); /// assert_...
<U: UnsignedWord>(self, n: U) -> Self { clear_bits_geq(self, n) } }
clear_bits_geq
identifier_name
clear_bits_geq.rs
use word::{Word, ToWord, UnsignedWord}; /// Clears all bits of `x` at position >= `bit`. /// /// # Panics /// /// If `bit >= bit_size()`. /// /// # Intrinsics: /// - BMI 2.0: bzhi. /// /// # Examples /// /// ``` /// use bitwise::word::*; /// /// assert_eq!(0b1111_0010u8.clear_bits_geq(5u8), 0b0001_0010u8); /// assert_...
}
{ clear_bits_geq(self, n) }
identifier_body
alarm_mutex.rs
use std::io::prelude::*; use std::time::{Instant, Duration}; use std::cmp::Ord; use std::thread; use std::sync::{Mutex, Arc}; struct Alarm { seconds: Duration, time: Instant, message: String, } impl Alarm { fn new(s: u64, m: String) -> Self { let s = Duration::from_secs(s); Alarm { ...
} } }
Ok(mut alarm_vec) => { alarm_vec.push(Alarm::new(seconds, message)); alarm_vec.sort_by(|a, b| b.time.cmp(&a.time)); }, Err(e) => panic!(format!("failed to lock mutex: {}", e)),
random_line_split
alarm_mutex.rs
use std::io::prelude::*; use std::time::{Instant, Duration}; use std::cmp::Ord; use std::thread; use std::sync::{Mutex, Arc}; struct Alarm { seconds: Duration, time: Instant, message: String, } impl Alarm { fn new(s: u64, m: String) -> Self { let s = Duration::from_secs(s); Alarm { ...
fn main() { let alarms = Arc::new(Mutex::new(Vec::<Alarm>::new())); start_alarm_thread(alarms.clone()); loop { let mut line = String::new(); print!("Alarm> "); match std::io::stdout().flush() { Ok(()) => {}, Err(error) => panic!(format!("error wh...
{ thread::spawn(move || { loop { let alarm = alarm_list.lock().unwrap().pop(); match alarm { Some(a) => { let now = Instant::now(); if a.time <= now { thread::yield_now(); } else { ...
identifier_body
alarm_mutex.rs
use std::io::prelude::*; use std::time::{Instant, Duration}; use std::cmp::Ord; use std::thread; use std::sync::{Mutex, Arc}; struct Alarm { seconds: Duration, time: Instant, message: String, } impl Alarm { fn
(s: u64, m: String) -> Self { let s = Duration::from_secs(s); Alarm { seconds: s, time: Instant::now() + s, message: m, } } } type AlarmList = Arc<Mutex<Vec<Alarm>>>; fn start_alarm_thread(alarm_list: AlarmList) { thread::spawn(move || { loop...
new
identifier_name
color.rs
//! Color use image::Rgb; use math::Vec3f; #[derive(Clone, Copy, Debug, Deserialize, PartialEq)] pub enum Color { Black, White, Red,
Cyan, Magenta, Yellow, Azure, Orange, Gray, Brightorange, DarkGreen, SkyBlue, Brown, DarkBrown, CornflowerBlue, Rgb(Vec3f), } impl Color { pub fn vec3f(&self) -> Vec3f { match *self { Color::Black => Vec3f { x: 0.0, y: 0.0, z: 0.0},...
Green, Blue,
random_line_split
color.rs
//! Color use image::Rgb; use math::Vec3f; #[derive(Clone, Copy, Debug, Deserialize, PartialEq)] pub enum Color { Black, White, Red, Green, Blue, Cyan, Magenta, Yellow, Azure, Orange, Gray, Brightorange, DarkGreen, SkyBlue, Brown, DarkBrown, Cornflow...
}
{ Color::Black }
identifier_body
color.rs
//! Color use image::Rgb; use math::Vec3f; #[derive(Clone, Copy, Debug, Deserialize, PartialEq)] pub enum
{ Black, White, Red, Green, Blue, Cyan, Magenta, Yellow, Azure, Orange, Gray, Brightorange, DarkGreen, SkyBlue, Brown, DarkBrown, CornflowerBlue, Rgb(Vec3f), } impl Color { pub fn vec3f(&self) -> Vec3f { match *self { Colo...
Color
identifier_name
adapters.rs
// Copyright 2016 The Grin Developers // // 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 agree...
(&self, peer_addrs: Vec<SocketAddr>) -> Result<(), p2p::Error> { debug!("Received {} peer addrs, saving.", peer_addrs.len()); for pa in peer_addrs { if let Ok(e) = self.peer_store.exists_peer(pa) { if e { continue; } } let peer = PeerData { addr: pa, capabilities: p2p::UNKNOWN, use...
peer_addrs_received
identifier_name
adapters.rs
// Copyright 2016 The Grin Developers // // 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 agree...
peer_store: Arc<PeerStore>, tx_pool: Arc<RwLock<pool::TransactionPool<PoolToChainAdapter>>>, syncer: OneTime<Arc<sync::Syncer>>, } impl NetAdapter for NetToChainAdapter { fn total_difficulty(&self) -> Difficulty { self.chain.total_difficulty() } fn transaction_received(&self, tx: core::Transaction) -> Result...
random_line_split
adapters.rs
// Copyright 2016 The Grin Developers // // 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 agree...
fn headers_received(&self, bhs: Vec<core::BlockHeader>) -> Result<(), p2p::Error> { // try to add each header to our header chain let mut added_hs = vec![]; for bh in bhs { let res = self.chain.process_block_header(&bh, self.chain_opts()); match res { Ok(_) => { added_hs.push(bh.hash()); } ...
{ let bhash = b.hash(); debug!("Received block {} from network, going to process.", bhash); // pushing the new block through the chain pipeline let res = self.chain.process_block(b, self.chain_opts()); if let Err(e) = res { debug!("Block {} refused by chain: {:?}", bhash, e); return Err(p2p::Erro...
identifier_body
image.rs
use std::io::{ Result, Write}; use core::color::Color; /// Types that can be converted to a [u8; 4] RGBA. trait ToRGBA255 { fn rgba255(&self) -> [u8; 4]; } impl ToRGBA255 for Color { fn rgba255(&self) -> [u8; 4] { let f = |x: f32| (x * 255.0) as u8; [ f(self.channels()[0]), f(self.c...
Ok(()) } pub fn set(&mut self, x: usize, y: usize, c: &Color) { self._data[x + (y * self._width)] = *c; } } // ------------------------ // Spectrum // ------------------------
random_line_split
image.rs
use std::io::{ Result, Write}; use core::color::Color; /// Types that can be converted to a [u8; 4] RGBA. trait ToRGBA255 { fn rgba255(&self) -> [u8; 4]; } impl ToRGBA255 for Color { fn rgba255(&self) -> [u8; 4] { let f = |x: f32| (x * 255.0) as u8; [ f(self.channels()[0]), f(self.c...
<T>(&self, out: &mut T) -> Result<()> where T: Write { // try!(write!(out, "P6 {} {} 255 ", self._width, self._height)); for color in &self._data { let channels = &color.rgba255()[0..3]; try!(out.write_all(&channels)); } Ok(()) } pub fn se...
writeppm
identifier_name
factor_int.rs
// http://rosettacode.org/wiki/Factors_of_an_integer fn
() { let target = 78i32; println!("Factors of integer {}:", target); let factors = factor_int(target); for f in factors { println!("{}", f); } } /// Compute the factors of an integer /// This method uses a simple check on each value between 1 and sqrt(x) to find /// pairs of factors fn fac...
main
identifier_name
factor_int.rs
// http://rosettacode.org/wiki/Factors_of_an_integer fn main() { let target = 78i32; println!("Factors of integer {}:", target); let factors = factor_int(target); for f in factors { println!("{}", f); } }
/// Compute the factors of an integer /// This method uses a simple check on each value between 1 and sqrt(x) to find /// pairs of factors fn factor_int(x: i32) -> Vec<i32> { let mut factors: Vec<i32> = Vec::new(); let bound: i32 = (x as f64).sqrt().floor() as i32; for i in 1i32..bound { if x % i ...
random_line_split
factor_int.rs
// http://rosettacode.org/wiki/Factors_of_an_integer fn main() { let target = 78i32; println!("Factors of integer {}:", target); let factors = factor_int(target); for f in factors { println!("{}", f); } } /// Compute the factors of an integer /// This method uses a simple check on each va...
} factors } #[test] fn test() { let result = factor_int(78i32); assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]); }
{ factors.push(i); factors.push(x / i); }
conditional_block
factor_int.rs
// http://rosettacode.org/wiki/Factors_of_an_integer fn main()
/// Compute the factors of an integer /// This method uses a simple check on each value between 1 and sqrt(x) to find /// pairs of factors fn factor_int(x: i32) -> Vec<i32> { let mut factors: Vec<i32> = Vec::new(); let bound: i32 = (x as f64).sqrt().floor() as i32; for i in 1i32..bound { if x % ...
{ let target = 78i32; println!("Factors of integer {}:", target); let factors = factor_int(target); for f in factors { println!("{}", f); } }
identifier_body
origin.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 std::sync::Arc; use url::{Host, Url}; use url::Origin as UrlOrigin; /// A representation of an [origin](https...
(&self) -> Origin { Origin { inner: self.inner.clone(), } } }
alias
identifier_name
origin.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 std::sync::Arc; use url::{Host, Url}; use url::Origin as UrlOrigin; /// A representation of an [origin](https...
/// https://html.spec.whatwg.org/multipage/#same-origin pub fn same_origin(&self, other: &Origin) -> bool { self.inner == other.inner } pub fn copy(&self) -> Origin { Origin { inner: Arc::new((*self.inner).clone()), } } pub fn alias(&self) -> Origin { ...
{ match *self.inner { UrlOrigin::Tuple(_, ref host, _) => Some(host), UrlOrigin::Opaque(..) => None, } }
identifier_body
origin.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 std::sync::Arc; use url::{Host, Url}; use url::Origin as UrlOrigin; /// A representation of an [origin](https...
}
}
random_line_split
vec.rs
use std::vec::IntoIter; use std::marker::PhantomData; use super::{Set, SetManager}; use super::sort::SortManager; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Error { IndexOutOfRange { index: usize, total: usize }, } pub struct VecSetIter<T, E> { iter: Option<IntoIter<T>>, _marker: PhantomData<E>...
} #[cfg(test)] mod tests { use super::{Error, Manager}; use super::super::{Set, SetManager}; fn run_basic<S>(mut set: S) where S: Set<T = u8, E = Error> { assert_eq!(set.size(), 0); assert_eq!(set.add(0), Ok(())); assert_eq!(set.size(), 1); assert_eq!(set.add(1), Ok(())); ...
random_line_split
vec.rs
use std::vec::IntoIter; use std::marker::PhantomData; use super::{Set, SetManager}; use super::sort::SortManager; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Error { IndexOutOfRange { index: usize, total: usize }, } pub struct VecSetIter<T, E> { iter: Option<IntoIter<T>>, _marker: PhantomData<E>...
<T> { _marker: PhantomData<T>, } impl<T> Manager<T> { pub fn new() -> Manager<T> { Manager { _marker: PhantomData, } } } impl<T> SetManager for Manager<T> { type S = Vec<T>; type E = (); fn make_set(&mut self, size_hint: Option<usize>) -> Result<Self::S, Self::E> {...
Manager
identifier_name
vec.rs
use std::vec::IntoIter; use std::marker::PhantomData; use super::{Set, SetManager}; use super::sort::SortManager; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Error { IndexOutOfRange { index: usize, total: usize }, } pub struct VecSetIter<T, E> { iter: Option<IntoIter<T>>, _marker: PhantomData<E>...
else { Ordering::Greater }); Ok(()) } } #[cfg(test)] mod tests { use super::{Error, Manager}; use super::super::{Set, SetManager}; fn run_basic<S>(mut set: S) where S: Set<T = u8, E = Error> { assert_eq!(set.size(), 0); assert_eq!(set.add(0), Ok(())); ...
{ Ordering::Less }
conditional_block
pinsrb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pinsrb_1() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(EB...
() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(RDI, Four, 1269005607, Some(OperandSize::Byte), None)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: N...
pinsrb_4
identifier_name
pinsrb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pinsrb_1() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(EB...
}
run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(RDI, Four, 1269005607, Some(OperandSize::Byte), None)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }...
random_line_split
pinsrb.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; fn pinsrb_1() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM6)), operand2: Some(Direct(EB...
fn pinsrb_4() { run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledDisplaced(RDI, Four, 1269005607, Some(OperandSize::Byte), None)), operand3: Some(Literal8(38)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None,...
{ run_test(&Instruction { mnemonic: Mnemonic::PINSRB, operand1: Some(Direct(XMM5)), operand2: Some(Direct(EDI)), operand3: Some(Literal8(12)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 32, 239, 12], OperandSize::Qword) }
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use clidispatch::io::IO; use cpython::*; use cpython_ext::wrap_pyio; pub fn init_module(py: Python, package...
( _py: Python, args: Vec<String>, fin: PyObject, fout: PyObject, ferr: Option<PyObject>, ) -> PyResult<i32> { let fin = wrap_pyio(fin); let fout = wrap_pyio(fout); let ferr = ferr.map(wrap_pyio); let mut io = IO::new(fin, fout, ferr); Ok(hgcommands::run_command(args, &mut io)) }...
run_py
identifier_name
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)] use clidispatch::io::IO; use cpython::*; use cpython_ext::wrap_pyio; pub fn init_module(py: Python, package...
{ let fin = wrap_pyio(fin); let fout = wrap_pyio(fout); let ferr = ferr.map(wrap_pyio); let mut io = IO::new(fin, fout, ferr); Ok(hgcommands::run_command(args, &mut io)) }
identifier_body
lib.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #![allow(non_camel_case_types)]
let name = [package, "commands"].join("."); let m = PyModule::new(py, &name)?; m.add( py, "run", py_fn!( py, run_py( args: Vec<String>, fin: PyObject, fout: PyObject, ferr: Option<PyObject> = None...
use clidispatch::io::IO; use cpython::*; use cpython_ext::wrap_pyio; pub fn init_module(py: Python, package: &str) -> PyResult<PyModule> {
random_line_split
dom_html_paragraph_element.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMNode; use DOMObject; use glib::GString; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerI...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMHTMLParagraphElement") } }
fmt
identifier_name
dom_html_paragraph_element.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMNode; use DOMObject; use glib::GString; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerI...
fn set_align(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_paragraph_element_set_align(self.as_ref().to_glib_none().0, value.to_glib_none().0); } } fn connect_property_align_notify<F: Fn(&Self) +'static>(&self, f: F) -> SignalHandlerId { unsa...
{ unsafe { from_glib_full(webkit2_webextension_sys::webkit_dom_html_paragraph_element_get_align(self.as_ref().to_glib_none().0)) } }
identifier_body
dom_html_paragraph_element.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use DOMElement; use DOMEventTarget; use DOMHTMLElement; use DOMNode; use DOMObject; use glib::GString; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerI...
unsafe extern "C" fn notify_align_trampoline<P, F: Fn(&P) +'static>(this: *mut webkit2_webextension_sys::WebKitDOMHTMLParagraphElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer) where P: IsA<DOMHTMLParagraphElement> { let f: &F = &*(f as *const F); f(&DO...
fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
random_line_split
pick_from_list.rs
use std::{io,fs}; use std::io::{Read, Write, BufReader, BufRead}; use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::str::FromStr; use std::env; fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> { let process = try!(c...
} } /// Asks the user to select a file from the filesystem, starting at directory `path`. /// /// Requires a function that produces the command as `cmd`, because commands aren't cloneable. pub fn pick_file<C>(cmd: C, path: PathBuf) -> io::Result<PathBuf> where C: Fn() -> Option<Command> { let mut curpath = pa...
random_line_split
pick_from_list.rs
use std::{io,fs}; use std::io::{Read, Write, BufReader, BufRead}; use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::str::FromStr; use std::env; fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> { let process = try!(c...
else { return Ok(newpath); } } } } /// Returns the user's preferred menu program from the `MENU` environment variable if it exists. /// /// Use `.as_mut()` on the returned value to turn in into an `Option<&mut Command>`. pub fn default_menu_cmd() -> Option<Command> { env::...
{ curpath = newpath; }
conditional_block
pick_from_list.rs
use std::{io,fs}; use std::io::{Read, Write, BufReader, BufRead}; use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::str::FromStr; use std::env; fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> { let process = try!(c...
{ env::var_os("MENU").map(|s| Command::new(s)) }
identifier_body
pick_from_list.rs
use std::{io,fs}; use std::io::{Read, Write, BufReader, BufRead}; use std::fs::{File, OpenOptions}; use std::path::PathBuf; use std::process::{Command, Stdio}; use std::str::FromStr; use std::env; fn pick_from_list_external<T: AsRef<str>>(cmd: &mut Command, items: &[T]) -> io::Result<String> { let process = try!(c...
<T: AsRef<str>>(items: &[T], prompt: &str) -> io::Result<String> { let mut tty = try!(OpenOptions::new().read(true).write(true).open("/dev/tty")); let pad_len = ((items.len() as f32).log10().floor() + 1.0) as usize; for (i, item) in items.iter().enumerate() { try!(tty.write_all(format!("{1:0$}. {2}\...
pick_from_list_internal
identifier_name
whitespace.rs
use nom::multispace; named!(comment<&str, &str>, delimited!( tag!("/*"), take_until!("*/"), tag!("*/") )); named!(space_or_comment<&str, &str>, alt!( multispace | comment )); named!(pub space<&str, ()>, fold_many1!( space_or_comment, (), |_, _| () )); named!(pub opt_space<&str, ()>, fold...
#[test] fn test_opt_space() { named!(test_parser<&str, &str>, do_parse!( tag!("(") >> opt_space >> res: take_while!(is_good) >> opt_space >> tag!(")") >> (res) ))...
{ named!(test_parser<&str, Vec<&str>>, wsc!(many0!( take_while!(is_good) ))); let input = "a /* b */ c / * d /**/ e "; assert_done!(test_parser(input), vec!["a", "c", "/", "*", "d", "e"]); }
identifier_body
whitespace.rs
use nom::multispace; named!(comment<&str, &str>, delimited!( tag!("/*"), take_until!("*/"), tag!("*/") )); named!(space_or_comment<&str, &str>, alt!( multispace | comment )); named!(pub space<&str, ()>, fold_many1!( space_or_comment, (), |_, _| () )); named!(pub opt_space<&str, ()>, fold...
() { named!(test_parser<&str, &str>, do_parse!( tag!("(") >> opt_space >> res: take_while!(is_good) >> opt_space >> tag!(")") >> (res) )); let input1 = "( a )"; ...
test_opt_space
identifier_name
whitespace.rs
use nom::multispace; named!(comment<&str, &str>, delimited!( tag!("/*"), take_until!("*/"), tag!("*/") )); named!(space_or_comment<&str, &str>, alt!( multispace | comment
named!(pub space<&str, ()>, fold_many1!( space_or_comment, (), |_, _| () )); named!(pub opt_space<&str, ()>, fold_many0!( space_or_comment, (), |_, _| () )); /// Transforms a parser to automatically consume whitespace and comments /// between each token. macro_rules! wsc( ($i:expr, $($arg...
));
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate sdl2; mod yuv; mod sdlui; use std::process::exit; use sdlui::{Channel, SdlUi, ViewFrame}; pub fn main()
}); let height: u32 = matches .value_of("HEIGHT") .unwrap() .parse() .unwrap_or_else(|e| { eprintln!("Invalid height: {}", e); exit(1) }); let multiplier: u32 = matches .value_of("MULTIPLIER") .unwrap_or("5") .parse() ...
{ let matches = clap_app!(yuvdiff => (version: "0.1") (about: "Diff YUV files") (@arg WIDTH: -w --width +takes_value +required "Width") (@arg HEIGHT: -h --height +takes_value +required "Height") (@arg CHANNEL: -c --channel +takes_value "Channel (y, u, v, c)") (@arg VI...
identifier_body
main.rs
#[macro_use] extern crate clap; extern crate sdl2; mod yuv; mod sdlui; use std::process::exit; use sdlui::{Channel, SdlUi, ViewFrame}; pub fn main() { let matches = clap_app!(yuvdiff => (version: "0.1") (about: "Diff YUV files") (@arg WIDTH: -w --width +takes_value +required "Width") ...
.unwrap_or("5") .parse() .unwrap_or_else(|e| { eprintln!("Invalid multiplier: {}", e); exit(1) }); let view: ViewFrame = matches .value_of("VIEW") .unwrap_or("a") .parse() .unwrap_or_else(|e| { eprintln!("Invalid frame: {}...
exit(1) }); let multiplier: u32 = matches .value_of("MULTIPLIER")
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate sdl2; mod yuv; mod sdlui; use std::process::exit; use sdlui::{Channel, SdlUi, ViewFrame}; pub fn
() { let matches = clap_app!(yuvdiff => (version: "0.1") (about: "Diff YUV files") (@arg WIDTH: -w --width +takes_value +required "Width") (@arg HEIGHT: -h --height +takes_value +required "Height") (@arg CHANNEL: -c --channel +takes_value "Channel (y, u, v, c)") (@arg...
main
identifier_name
parser.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/. */ //! The context within which CSS code is parsed. use context::QuirksMode; use cssparser::{Parser, SourceLocation,...
UnicodeRange::parse(input).map_err(|e| e.into()) } }
} impl Parse for UnicodeRange { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
random_line_split
parser.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/. */ //! The context within which CSS code is parsed. use context::QuirksMode; use cssparser::{Parser, SourceLocation,...
impl Parse for UnicodeRange { fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { UnicodeRange::parse(input).map_err(|e| e.into()) } }
<T as OneOrMoreSeparated>::S::parse(input, |i| T::parse(context, i)) } }
identifier_body
parser.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/. */ //! The context within which CSS code is parsed. use context::QuirksMode; use cssparser::{Parser, SourceLocation,...
( stylesheet_origin: Origin, url_data: &'a UrlExtraData, error_reporter: &'a ParseErrorReporter, line_number_offset: u64, parsing_mode: ParsingMode, quirks_mode: QuirksMode ) -> ParserContext<'a> { ParserContext { stylesheet_origin: stylesheet_orig...
new_with_line_number_offset
identifier_name
any_ambiguous_aliases_generated.rs
// automatically generated by the FlatBuffers compiler, do not modify extern crate flatbuffers; use std::mem; use std::cmp::Ordering; use self::flatbuffers::{EndianScalar, Follow}; use super::*; #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub cons...
(&self) -> AnyAmbiguousAliases { match self { Self::NONE => AnyAmbiguousAliases::NONE, Self::M1(_) => AnyAmbiguousAliases::M1, Self::M2(_) => AnyAmbiguousAliases::M2, Self::M3(_) => AnyAmbiguousAliases::M3, } } pub fn pack(&self, fbb: &mut flatbuffers::FlatBufferBuilder) -> Option<fl...
any_ambiguous_aliases_type
identifier_name
any_ambiguous_aliases_generated.rs
// automatically generated by the FlatBuffers compiler, do not modify extern crate flatbuffers; use std::mem; use std::cmp::Ordering; use self::flatbuffers::{EndianScalar, Follow}; use super::*; #[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] pub cons...
pub enum AnyAmbiguousAliasesT { NONE, M1(Box<MonsterT>), M2(Box<MonsterT>), M3(Box<MonsterT>), } impl Default for AnyAmbiguousAliasesT { fn default() -> Self { Self::NONE } } impl AnyAmbiguousAliasesT { pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases { match self { Self::NONE...
pub struct AnyAmbiguousAliasesUnionTableOffset {} #[allow(clippy::upper_case_acronyms)] #[non_exhaustive] #[derive(Debug, Clone, PartialEq)]
random_line_split
main.rs
#[macro_use] extern crate nom; extern crate ansi_term; extern crate getopts; use getopts::Options; use std::io::prelude::*; use std::fs::File; use std::env; mod ast; mod parser; mod typechecker; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options] FILE", program); print!("...
() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let opts = initialize_args(); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&program, opts)...
main
identifier_name
main.rs
#[macro_use] extern crate nom; extern crate ansi_term; extern crate getopts; use getopts::Options; use std::io::prelude::*; use std::fs::File; use std::env; mod ast; mod parser; mod typechecker; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options] FILE", program); print!("...
}; if print_ast { print!("{}", ast); } match typechecker::check(ast) { Ok(_) => (), Err(s) => { println!("Typechecker error: {}", s); return; } } }
println!("{}", s); return; }
random_line_split
main.rs
#[macro_use] extern crate nom; extern crate ansi_term; extern crate getopts; use getopts::Options; use std::io::prelude::*; use std::fs::File; use std::env; mod ast; mod parser; mod typechecker; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options] FILE", program); print!("...
fn main() { let args: Vec<String> = env::args().collect(); let program = args[0].clone(); let opts = initialize_args(); let matches = match opts.parse(&args[1..]) { Ok(m) => { m } Err(f) => { panic!(f.to_string()) } }; if matches.opt_present("h") { print_usage(&progr...
{ let mut opts = Options::new(); opts.optopt("O", "", "set optimization level", "[0-3]"); opts.optflag("h", "help", "print this help menu"); opts.optflag("", "ast", "print the ast"); return opts; }
identifier_body
main.rs
#[macro_use] extern crate nom; extern crate ansi_term; extern crate getopts; use getopts::Options; use std::io::prelude::*; use std::fs::File; use std::env; mod ast; mod parser; mod typechecker; fn print_usage(program: &str, opts: Options) { let brief = format!("Usage: {} [options] FILE", program); print!("...
let print_ast = matches.opt_present("ast"); let filename = if!matches.free.is_empty() { matches.free[0].clone() } else { print_usage(&program, opts); return; }; let mut input = File::open(filename).unwrap(); let mut code = String::new(); input.read_to_string(&mut ...
{ print_usage(&program, opts); return; }
conditional_block
main.rs
#![feature(io)] #![feature(os)] #![feature(env)] #![feature(path)] #![feature(collections)] use std::old_io; use std::old_io::fs; use std::old_io::process::{Command}; use std::old_path::Path; use std::env; mod ash; fn main()
Some(p) => cwd = p, None => println!("Error: Can not get home directory!") } continue; } let path: Option<Path> = if args[0].starts_with("~") { // ~/projects match env::home_dir() { Some(e) => { let dir = e.join(args[0].slic...
{ println!("ash: A shell"); println!("Incredibly in beta"); println!("May eat your left shoes."); let mut cwd = env::current_dir().unwrap(); loop { print!("{}", ash::format::format(&cwd)); let rawinput = old_io::stdin().read_line().ok().expect("Error Occured"); let input = rawinput.as_slice().tr...
identifier_body
main.rs
#![feature(io)] #![feature(os)] #![feature(env)] #![feature(path)] #![feature(collections)] use std::old_io; use std::old_io::fs; use std::old_io::process::{Command}; use std::old_path::Path; use std::env; mod ash; fn main() { println!("ash: A shell"); println!("Incredibly in beta"); println!("May eat your le...
}, Err(e) => println!("No such file or directory: \"{}\"", args[0]) } } None => println!("Failed to locate path") } } "exit" => { println!("Goodbye!"); break; } _ => { let process = Command::new(cmd).cwd...
{ cwd = new }
conditional_block
main.rs
#![feature(io)] #![feature(os)] #![feature(env)] #![feature(path)] #![feature(collections)] use std::old_io; use std::old_io::fs; use std::old_io::process::{Command}; use std::old_path::Path; use std::env; mod ash; fn
() { println!("ash: A shell"); println!("Incredibly in beta"); println!("May eat your left shoes."); let mut cwd = env::current_dir().unwrap(); loop { print!("{}", ash::format::format(&cwd)); let rawinput = old_io::stdin().read_line().ok().expect("Error Occured"); let input = rawinput.as_slice()...
main
identifier_name
main.rs
#![feature(io)] #![feature(os)] #![feature(env)] #![feature(path)] #![feature(collections)] use std::old_io; use std::old_io::fs; use std::old_io::process::{Command}; use std::old_path::Path; use std::env; mod ash; fn main() { println!("ash: A shell"); println!("Incredibly in beta"); println!("May eat your le...
continue; } let path: Option<Path> = if args[0].starts_with("~") { // ~/projects match env::home_dir() { Some(e) => { let dir = e.join(args[0].slice_from(2)); //[~/] Some(dir) }, //hacky but whatever None => Path::new_op...
//go home match env::home_dir() { Some(p) => cwd = p, None => println!("Error: Can not get home directory!") }
random_line_split
reverse_graph.rs
use crate::core::{ property::{AddEdge, RemoveEdge}, Directed, Ensure, Graph, GraphDerefMut, GraphMut, }; use delegate::delegate; use std::borrow::Borrow; #[derive(Debug)] pub struct ReverseGraph<C: Ensure>(C) where C::Graph: Graph<Directedness = Directed>; impl<C: Ensure> ReverseGraph<C> where C::Graph: Graph<Dir...
} impl<C: Ensure + GraphDerefMut> AddEdge for ReverseGraph<C> where C::Graph: AddEdge<Directedness = Directed>, { fn add_edge_weighted( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, weight: Self::EdgeWeight, ) -> Result<(), ()> { self.0.graph_mut().add_edge_weighted(sink...
{ Box::new(self.0.graph_mut().edges_between_mut(sink, source)) }
identifier_body
reverse_graph.rs
use crate::core::{ property::{AddEdge, RemoveEdge}, Directed, Ensure, Graph, GraphDerefMut, GraphMut, }; use delegate::delegate; use std::borrow::Borrow; #[derive(Debug)] pub struct ReverseGraph<C: Ensure>(C) where C::Graph: Graph<Directedness = Directed>; impl<C: Ensure> ReverseGraph<C> where C::Graph: Graph<Dir...
C::Graph: GraphMut<Directedness = Directed>, { delegate! { to self.0.graph_mut() { fn all_vertices_weighted_mut<'a>(&'a mut self) -> Box<dyn 'a + Iterator<Item= (Self::Vertex, &'a mut Self::VertexWeight)>>; } } fn edges_between_mut<'a: 'b, 'b>( &'a mut self, source: impl 'b + Borrow<Self::Vertex>, ...
} } impl<C: Ensure + GraphDerefMut> GraphMut for ReverseGraph<C> where
random_line_split
reverse_graph.rs
use crate::core::{ property::{AddEdge, RemoveEdge}, Directed, Ensure, Graph, GraphDerefMut, GraphMut, }; use delegate::delegate; use std::borrow::Borrow; #[derive(Debug)] pub struct ReverseGraph<C: Ensure>(C) where C::Graph: Graph<Directedness = Directed>; impl<C: Ensure> ReverseGraph<C> where C::Graph: Graph<Dir...
( &mut self, source: impl Borrow<Self::Vertex>, sink: impl Borrow<Self::Vertex>, weight: Self::EdgeWeight, ) -> Result<(), ()> { self.0.graph_mut().add_edge_weighted(sink, source, weight) } } impl<C: Ensure + GraphDerefMut> RemoveEdge for ReverseGraph<C> where C::Graph: RemoveEdge<Directedness = Directed...
add_edge_weighted
identifier_name
physics.rs
use super::{Unit, ToUnit}; #[deriving(Eq, Ord)] pub struct Vec2 { pub x: Unit, pub y: Unit, } impl Vec2 { pub fn new<A: ToUnit, B: ToUnit>(x: A, y: B) -> Vec2 { Vec2 { x: x.to_unit(), y: y.to_unit(), } } pub fn norm(&self) -> Vec2 { let len = self.l...
(&self) -> Vec2 { *self } } impl Add<Vec2, Vec2> for Vec2 { fn add(&self, rhs: &Vec2) -> Vec2 { Vec2 { x: self.x + rhs.x, y: self.y + rhs.y, } } } impl<T: ToUnit> Mul<T, Vec2> for Vec2 { fn mul(&self, rhs: &T) -> Vec2 { let a = rhs.to_unit(); ...
to_vec
identifier_name