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
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #![allow(clippy::large_enum_variant)] pub mod devices; pub mod udev; pub mod uevent; use std::{ cmp::Ordering, collections::BTreeSet, hash::{Hash, Hasher...
() { let xs: OrdSet<DevicePath> = ordset![ "/dev/disk/by-id/dm-uuid-part1-mpath-3600140550e41a841db244a992c31e7df".into(), "/dev/mapper/mpathd1".into(), "/dev/disk/by-uuid/b4550256-cf48-4013-8363-bfee5f52da12".into(), "/dev/disk/by-partuuid/d643e32f-b6b9-4863-af8f...
test_device_path_ordering
identifier_name
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #![allow(clippy::large_enum_variant)] pub mod devices; pub mod udev; pub mod uevent; use std::{ cmp::Ordering, collections::BTreeSet, hash::{Hash, Hasher...
libzfs_types::VDev::Root { children, spares, cache, .. } => vec![children, spares, cache] .into_iter() .flatten() .flat_map(get_vdev_paths) .collect(), } } impl Ord for DevicePath { fn cmp(&self, other: ...
{ children.iter().flat_map(get_vdev_paths).collect() }
conditional_block
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #![allow(clippy::large_enum_variant)] pub mod devices; pub mod udev; pub mod uevent; use std::{ cmp::Ordering, collections::BTreeSet, hash::{Hash, Hasher...
pub zed_events: ZedEvents, pub local_mounts: HashSet<mount::Mount>, } impl State { pub fn new() -> Self { State { uevents: HashMap::new(), zed_events: HashMap::new(), local_mounts: HashSet::new(), } } } ...
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] pub struct State { pub uevents: UEvents,
random_line_split
model_checker.rs
// Copyright 2014 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
(meta_item: MetaItem_) -> InternedString { match meta_item { MetaWord(name) | MetaList(name, _) | MetaNameValue(name, _) => name } } fn match_model(cx: &ExtCtxt, info: AttributeInfo, meta_item: &P<MetaItem>) -> AttributeInfo { let model = match (info.model, meta_item.node.clone()) { (UnitValue(va...
meta_item_name
identifier_name
model_checker.rs
// Copyright 2014 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
fn match_meta_item(cx: &ExtCtxt, model: AttributeArray, meta_item: &P<MetaItem>) -> AttributeArray { let meta_name = meta_item_name(meta_item.node.clone()); let mut attr_exists = false; let model = model.into_iter().map(|info| if info.name == meta_name { attr_exists = true; match_model(cx, i...
{ let meta_item = attr.node.value; match_meta_item(cx, model, &meta_item) }
identifier_body
model_checker.rs
// Copyright 2014 Pierre Talbot (IRCAM) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to...
{ value.update(cx, (), span) } fn match_lit(cx: &ExtCtxt, mlit: AttributeLitModel, lit: Lit) -> AttributeLitModel { let sp = lit.span; match (mlit, lit.node.clone()) { (MLitStr(value), LitStr(s, style)) => MLitStr(value.update(cx, (s, style), sp)), (MLitBinary(value), LitBinary(val)) => MLitBinary(value....
}; AttributeInfo { name: info.name, desc: info.desc, model: model } } fn match_value(cx: &ExtCtxt, value: AttributeValue<()>, span: Span) -> AttributeValue<()>
random_line_split
bookmarks.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 cocoa::base::*; use cocoa::foundation::*; use objc::declare::ClassDecl; use objc::runtime::{Class, Object, Sel...
_sel: Sel, _outlineview: id, _index: NSInteger, _item: id) -> id { nil } extern "C" fn is_item_expandable(_this...
{ /* NShellBookmark */ { let superclass = Class::get("NSObject").unwrap(); let mut newclass = ClassDecl::new("NSShellBookmark", superclass).unwrap(); newclass.add_ivar::<id>("link"); newclass.add_ivar::<id>("name"); newclass.register(); } /* NSShellBookmarks */ ...
identifier_body
bookmarks.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 cocoa::base::*; use cocoa::foundation::*; use objc::declare::ClassDecl; use objc::runtime::{Class, Object, Sel...
(_this: &Object, _sel: Sel, _outlineview: id, _column: id, _item: id) -> id { nil } // FIXME: Yeah! Outlets, we want...
object_value
identifier_name
bookmarks.rs
* 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 cocoa::base::*; use cocoa::foundation::*; use objc::declare::ClassDecl; use objc::runtime::{Class, Object, Sel}; pub fn register() { /* NShellBookmark */ { let sup...
/* This Source Code Form is subject to the terms of the Mozilla Public
random_line_split
octopus.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ /// Return a DAG with cross and octopus merges. pub fn
() -> Vec<Vec<usize>> { let parents = drawdag::parse( r#" r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r00 r01 r02 r03 r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r2...
cross_octopus
identifier_name
octopus.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ /// Return a DAG with cross and octopus merges. pub fn cross_octopus() -> Vec<Vec<usize>> { let parents = drawdag::parse( r#" ...
); (0..=32) .map(|i| { parents[&format!("r{:02}", i)] .iter() .map(|p| p.trim_start_matches('r').parse::<usize>().unwrap()) .collect() }) .collect() }
"#,
random_line_split
octopus.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ /// Return a DAG with cross and octopus merges. pub fn cross_octopus() -> Vec<Vec<usize>>
(0..=32) .map(|i| { parents[&format!("r{:02}", i)] .iter() .map(|p| p.trim_start_matches('r').parse::<usize>().unwrap()) .collect() }) .collect() }
{ let parents = drawdag::parse( r#" r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 r28 r29 r30 r31 r32 |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ |\ r00 r01 r02 r03 r04 r05 r06 r07 r08 r09 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 r23 r24 r25 r26 r27 ...
identifier_body
newtype.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let myval = mytype(Mytype{compute: compute, val: 30}); printfln!("%d", compute(myval)); assert_eq!((myval.compute)(myval), 50); }
main
identifier_name
newtype.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. //
// except according to those terms. struct mytype(Mytype); struct Mytype {compute: extern fn(mytype) -> int, val: int} fn compute(i: mytype) -> int { return i.val + 20; } pub fn main() { let myval = mytype(Mytype{compute: compute, val: 30}); printfln!("%d", compute(myval)); assert_eq!((myval.compute)(my...
// 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
random_line_split
ex5.rs
use std; //============================================================================== struct Complex { real : f32, imag : f32 } impl Complex { fn new(real: f32, imag: f32) -> Complex { Complex { real: real, imag: imag } } fn to_string(&self) -> String { format!("{}{:+}i", self...
} impl std::cmp::PartialOrd for Position { fn partial_cmp(&self, other: &Position) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl std::clone::Clone for Position { fn clone(&self) -> Position { Position { x : self.x, y: self.y } // Or, derive Copy at Position and re...
{ let abs = self.x * self.x + self.y * self.y; let abs_other = other.x * other.x + other.y * other.y; abs.cmp(&abs_other) }
identifier_body
ex5.rs
use std; //============================================================================== struct Complex { real : f32, imag : f32 } impl Complex { fn new(real: f32, imag: f32) -> Complex { Complex { real: real, imag: imag } }
} fn add(&self, v: Complex) -> Complex { Complex { real: self.real + v.real, imag: self.imag + v.imag } } fn times_ten(&mut self) { self.real *= 10.0; self.imag *= 10.0; } fn abs(&self) -> f32 { (self.real * self.real + self.imag * self.imag).sqrt() } } fn...
fn to_string(&self) -> String { format!("{}{:+}i", self.real, self.imag)
random_line_split
ex5.rs
use std; //============================================================================== struct Complex { real : f32, imag : f32 } impl Complex { fn new(real: f32, imag: f32) -> Complex { Complex { real: real, imag: imag } } fn to_string(&self) -> String { format!("{}{:+}i", self...
{ val : u32 } struct S2 { val : f32 } impl Draw for S1 { fn draw(&self) { println!("*** {} ***", self.val); } } impl Draw for S2 { fn draw(&self) { println!("*** {} ***", self.val); } } fn draw_object(obj : &Draw) { obj.draw(); } fn ex_5_2() { println!("\n==========...
S1
identifier_name
eval_definitions.rs
use crate::helpers::{values::*, *}; use ostrov::errors::RuntimeError::*; #[test] fn define_with_one_arg()
#[test] fn define_with_two_args() { assert_eval_val("(define x 2)", unspecified()); assert_eval( "(define x 2) (= x 2)", "#t", ); assert_eval( "(define x 9) (define x 10) x", "10", ); assert_eval( ...
{ assert_eval_val("(define x)", unspecified()); assert_eval_val( "(define x) x", unspecified(), ); }
identifier_body
eval_definitions.rs
use crate::helpers::{values::*, *}; use ostrov::errors::RuntimeError::*; #[test] fn define_with_one_arg() { assert_eval_val("(define x)", unspecified()); assert_eval_val( "(define x) x", unspecified(), ); } #[test] fn define_with_two_args() { assert_eval_val("(d...
() { assert_eval( "(define f (lambda (x) 1)) (f 9)", "1", ); } #[test] fn define_procedure_with_fixed_args() { assert_eval_val("(define (x) 3)", unspecified()); } #[test] fn define_procedure_with_varargs() { assert_eval_val("(define (x a. b) 3)", unspecified()); } ...
define_with_one_arg_lambda
identifier_name
eval_definitions.rs
use crate::helpers::{values::*, *}; use ostrov::errors::RuntimeError::*; #[test] fn define_with_one_arg() { assert_eval_val("(define x)", unspecified()); assert_eval_val( "(define x) x", unspecified(), ); } #[test] fn define_with_two_args() { assert_eval_val("(d...
(= x 2)", "#t", ); assert_eval( "(define x 9) (define x 10) x", "10", ); assert_eval( "(define x 9) (define y x) y", "9", ); } #[test] fn define_with_one_arg_l...
random_line_split
encoder.rs
extern crate getopts; extern crate lt; use std::env; use std::io::{self, Write}; use std::fs::File; use getopts::{Options, Matches}; use lt::sampler::params::LTBlockSamplerParams; use lt::encode; fn parameterize(default: LTBlockSamplerParams, matches: Matches) -> LTBlockSamplerParams { let mut params = default; ...
let input_fn = matches.opt_str("f").unwrap(); let mut f = match File::open(input_fn) { Ok(file) => file, Err(e) => panic!("{}", e) }; // Parameterize LT sampler using options let num_blocks: u32 = match matches.opt_str("k").unwrap().parse() { Ok(k) => k, Err(e) => panic!("Error parsing k: {}"...
{ let args: Vec<String> = env::args().collect(); let mut options = Options::new(); options.reqopt("f", "input_file", "File to transmit", "FILE"); options.reqopt("k", "num_blocks", "Number of blocks to divide the file into for transmission", ""); options.optopt("c", "c", "C parameter to block sampler", ""); ...
identifier_body
encoder.rs
extern crate getopts; extern crate lt; use std::env; use std::io::{self, Write}; use std::fs::File; use getopts::{Options, Matches}; use lt::sampler::params::LTBlockSamplerParams; use lt::encode;
// Add c to opts params = match matches.opt_str("c") { Some(c) => params.c(c.parse::<f64>().unwrap()), None => params }; // Add delta to opts params = match matches.opt_str("d") { Some(delta) => params.delta(delta.parse::<f64>().unwrap()), None => params }; // Add seed to opts params = m...
fn parameterize(default: LTBlockSamplerParams, matches: Matches) -> LTBlockSamplerParams { let mut params = default;
random_line_split
encoder.rs
extern crate getopts; extern crate lt; use std::env; use std::io::{self, Write}; use std::fs::File; use getopts::{Options, Matches}; use lt::sampler::params::LTBlockSamplerParams; use lt::encode; fn parameterize(default: LTBlockSamplerParams, matches: Matches) -> LTBlockSamplerParams { let mut params = default; ...
() { let args: Vec<String> = env::args().collect(); let mut options = Options::new(); options.reqopt("f", "input_file", "File to transmit", "FILE"); options.reqopt("k", "num_blocks", "Number of blocks to divide the file into for transmission", ""); options.optopt("c", "c", "C parameter to block sampler", "")...
main
identifier_name
linear.rs
use autograd::{Function, FuncIntf, FuncDelegate, FIWrap}; use tensor::{OptTensorKindList, TensorKindList}; impl_func!(LinearF); impl FuncIntf for LinearF { fn forward(&mut self, input_list: &mut TensorKindList) -> TensorKindList { self.save_for_backward(input_list); let (input, weight) = (input_li...
}; output.push(grad_weight); if tensorlist.len() > 0 && needs_input_grad[2] { let grad_bias = grad_output.sum_reduce(0, false); output.push(Some(grad_bias)); } output } }
output.push(grad_input); let grad_weight = if needs_input_grad[1] { Some(grad_output.t().mm(input)) } else { None
random_line_split
linear.rs
use autograd::{Function, FuncIntf, FuncDelegate, FIWrap}; use tensor::{OptTensorKindList, TensorKindList}; impl_func!(LinearF); impl FuncIntf for LinearF { fn forward(&mut self, input_list: &mut TensorKindList) -> TensorKindList
fn backward(&mut self, grad_output_list: &mut OptTensorKindList) -> OptTensorKindList { let tensorlist = self.saved_tensors(); let grad_output_ = grad_output_list.remove(0); let needs_input_grad = self.needs_input_grad(); let grad_output = match grad_output_ { Some(f) =>...
{ self.save_for_backward(input_list); let (input, weight) = (input_list.remove(0), input_list.remove(0)); let mut output = input.new(()).resize_([input.size()[0], weight.size()[0]]); output.zero_().addmm_(0, 1, &input, &weight.t()); if input_list.len() != 0 { let bias...
identifier_body
linear.rs
use autograd::{Function, FuncIntf, FuncDelegate, FIWrap}; use tensor::{OptTensorKindList, TensorKindList}; impl_func!(LinearF); impl FuncIntf for LinearF { fn forward(&mut self, input_list: &mut TensorKindList) -> TensorKindList { self.save_for_backward(input_list); let (input, weight) = (input_li...
(&mut self, grad_output_list: &mut OptTensorKindList) -> OptTensorKindList { let tensorlist = self.saved_tensors(); let grad_output_ = grad_output_list.remove(0); let needs_input_grad = self.needs_input_grad(); let grad_output = match grad_output_ { Some(f) => f, ...
backward
identifier_name
linear.rs
use autograd::{Function, FuncIntf, FuncDelegate, FIWrap}; use tensor::{OptTensorKindList, TensorKindList}; impl_func!(LinearF); impl FuncIntf for LinearF { fn forward(&mut self, input_list: &mut TensorKindList) -> TensorKindList { self.save_for_backward(input_list); let (input, weight) = (input_li...
else { None }; output.push(grad_input); let grad_weight = if needs_input_grad[1] { Some(grad_output.t().mm(input)) } else { None }; output.push(grad_weight); if tensorlist.len() > 0 && needs_input_grad[2] { let grad...
{ Some(grad_output.mm(weight)) }
conditional_block
mx.rs
extern crate c_ares_sys; extern crate libc; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::slice; use std::str; use error::AresError; use utils::ares_error; /// The result of a successful MX lookup. pub struct MXResults { mx_reply: *mut c_ares_sys::Struct_ares_mx_reply, ...
<'a> { mx_reply: *const c_ares_sys::Struct_ares_mx_reply, phantom: PhantomData<&'a c_ares_sys::Struct_ares_mx_reply>, } impl MXResults { /// Obtain an `MXResults` from the response to an MX lookup. pub fn parse_from(data: &[u8]) -> Result<MXResults, AresError> { let mut mx_reply: *mut c_ares_sy...
MXResult
identifier_name
mx.rs
extern crate c_ares_sys; extern crate libc; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::slice; use std::str; use error::AresError; use utils::ares_error; /// The result of a successful MX lookup. pub struct MXResults { mx_reply: *mut c_ares_sys::Struct_ares_mx_reply, ...
/// Returns an iterator over the `MXResult` values in this `MXResults`. pub fn iter(&self) -> MXResultsIterator { MXResultsIterator { next: self.mx_reply, phantom: PhantomData, } } } pub struct MXResultsIterator<'a> { next: *const c_ares_sys::Struct_ares_mx_rep...
{ MXResults { mx_reply: mx_reply, phantom: PhantomData, } }
identifier_body
mx.rs
extern crate c_ares_sys; extern crate libc; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::slice; use std::str; use error::AresError; use utils::ares_error; /// The result of a successful MX lookup. pub struct MXResults { mx_reply: *mut c_ares_sys::Struct_ares_mx_reply, ...
Err(ares_error(status)) } else { let data = slice::from_raw_parts(abuf, alen as usize); MXResults::parse_from(data) }; handler(result); }
let handler: Box<F> = mem::transmute(arg); let result = if status != c_ares_sys::ARES_SUCCESS {
random_line_split
mx.rs
extern crate c_ares_sys; extern crate libc; use std::ffi::CStr; use std::marker::PhantomData; use std::mem; use std::ptr; use std::slice; use std::str; use error::AresError; use utils::ares_error; /// The result of a successful MX lookup. pub struct MXResults { mx_reply: *mut c_ares_sys::Struct_ares_mx_reply, ...
else { let data = slice::from_raw_parts(abuf, alen as usize); MXResults::parse_from(data) }; handler(result); }
{ Err(ares_error(status)) }
conditional_block
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/. */ #![feature(append)] #![feature(arc_unique)] #![feature(box_str)] #![feature(box_syntax)] #![feature(cell_extras)] ...
#[macro_use] extern crate log; #[macro_use] extern crate bitflags; #[macro_use] #[no_link] extern crate plugins as servo_plugins; extern crate net_traits; #[macro_use] extern crate profile_traits; #[macro_use] extern crate util; extern crate azure; extern crate canvas_traits; extern crate clock_ticks; extern crate...
#![plugin(string_cache_plugin)] #![plugin(plugins)]
random_line_split
drawevent.rs
/// Event log for a drawing session /// Menu selections must pass through here to ensure they can be referenced /// Motion events can be shoved in wherever, though /// TODO: replay /// use timestamps on point events, rather than Frame events, so writing can be done from one /// thread /// think about how to make shader...
//fn get_event(&self, idx: usize) -> Option<&DrawEvent> { //self.eventlist.as_slice().get(idx) //} } #[inline] #[allow(unused)] pub fn handle_event<'a>(gl: &mut ::glinit::GLInit<'a>, events: &mut Events<'a>, queue: &mut ::point::PointProducer, eventidx: i32) -> event_stream::EventState { // FIXME...
{ //self.eventlist.clear(); }
identifier_body
drawevent.rs
/// Event log for a drawing session /// Menu selections must pass through here to ensure they can be referenced /// Motion events can be shoved in wherever, though /// TODO: replay /// use timestamps on point events, rather than Frame events, so writing can be done from one /// thread /// think about how to make shader...
Done, Frame, NoFrame, } pub struct EventStream { position: i32, pub consumer: ::glpoint::MotionEventConsumer, producer: ::glpoint::MotionEventProducer, } impl EventStream { pub fn new() -> EventStream { let (consumer, producer) = ::...
use core::prelude::*; use drawevent::{Events, handle_event}; #[derive(Copy)] pub enum EventState {
random_line_split
drawevent.rs
/// Event log for a drawing session /// Menu selections must pass through here to ensure they can be referenced /// Motion events can be shoved in wherever, though /// TODO: replay /// use timestamps on point events, rather than Frame events, so writing can be done from one /// thread /// think about how to make shader...
(&mut self, script: Option<MString>) -> GLResult<DrawObjectIndex<LuaScript>> { let initopt: LuaUnfilledValues = script; self.luascripts.push_object(initopt) } pub fn use_interpolator(&mut self, idx: DrawObjectIndex<LuaScript>) -> GLResult<&'a LuaScript> { //self.eventlist.push(DrawEvent...
load_interpolator
identifier_name
etcd_result.rs
use super::etcd_node::EtcdNode; use rustc_serialize::json; #[allow(dead_code)] #[derive(Debug)] pub struct EtcdResult { /// action: the action of the request that was just made. pub action: String, /// the node upon which the request was made pub node: Option<EtcdNode>, /// the previous node if there was ...
fn node_from_json(key: &'static str, result_obj: &json::Object) -> Option<EtcdNode> { // get the json for the node let node_obj: &json::Json = match result_obj.get(key) { Some(o) => o, None => return None, }; // extract the node return match node_obj.as_object() { ...
{ let node = EtcdResult::node_from_json("node", obj); let prev_node = EtcdResult::node_from_json("prevNode", obj); let result_action: Option<&json::Json> = obj.get("action"); return EtcdResult{ action: result_action.unwrap().as_string().unwrap().to_string(), node: node, previous_node:...
identifier_body
etcd_result.rs
use super::etcd_node::EtcdNode; use rustc_serialize::json; #[allow(dead_code)] #[derive(Debug)] pub struct EtcdResult { /// action: the action of the request that was just made.
/// the node upon which the request was made pub node: Option<EtcdNode>, /// the previous node if there was one pub previous_node: Option<EtcdNode>, /// X-Etcd-Index is the current etcd index as explained above. pub x_etcd_index: i64, /// X-Raft-Index is similar to the etcd index but is for the underly...
pub action: String,
random_line_split
etcd_result.rs
use super::etcd_node::EtcdNode; use rustc_serialize::json; #[allow(dead_code)] #[derive(Debug)] pub struct EtcdResult { /// action: the action of the request that was just made. pub action: String, /// the node upon which the request was made pub node: Option<EtcdNode>, /// the previous node if there was ...
(key: &'static str, result_obj: &json::Object) -> Option<EtcdNode> { // get the json for the node let node_obj: &json::Json = match result_obj.get(key) { Some(o) => o, None => return None, }; // extract the node return match node_obj.as_object() { Some(o) => Some(Et...
node_from_json
identifier_name
numeric_literal.rs
use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind}; use std::iter; #[derive(Debug, PartialEq, Copy, Clone)] pub enum Radix { Binary, Octal, Decimal, Hexadecimal, } impl Radix { /// Returns a reasonable digit group size for this radix. #[must_use] fn suggest_grouping(self) -> usiz...
#[derive(Debug)] pub struct NumericLiteral<'a> { /// Which radix the literal was represented in. pub radix: Radix, /// The radix prefix, if present. pub prefix: Option<&'a str>, /// The integer part of the number. pub integer: &'a str, /// The fraction part of the number. pub fraction...
{ NumericLiteral::new(lit, type_suffix, float).format() }
identifier_body
numeric_literal.rs
use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind}; use std::iter; #[derive(Debug, PartialEq, Copy, Clone)] pub enum Radix { Binary, Octal, Decimal, Hexadecimal, } impl Radix { /// Returns a reasonable digit group size for this radix. #[must_use] fn suggest_grouping(self) -> usiz...
if float { for (i, c) in digits.char_indices() { match c { '.' => { integer = &digits[..i]; fraction = Some(&digits[i + 1..]); }, 'e' | 'E' => { let ex...
let mut exponent = None;
random_line_split
numeric_literal.rs
use rustc_ast::ast::{Lit, LitFloatType, LitIntType, LitKind}; use std::iter; #[derive(Debug, PartialEq, Copy, Clone)] pub enum Radix { Binary, Octal, Decimal, Hexadecimal, } impl Radix { /// Returns a reasonable digit group size for this radix. #[must_use] fn suggest_grouping(self) -> usiz...
(&self) -> bool { self.radix == Radix::Decimal } pub fn split_digit_parts(digits: &str, float: bool) -> (&str, Option<&str>, Option<(&str, &str)>) { let mut integer = digits; let mut fraction = None; let mut exponent = None; if float { for (i, c) in digits.c...
is_decimal
identifier_name
io.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...
{ buf: BufWriter<File>, // This is not necessarily position in the underlying file, // but rather current position in the sink. pos: u64, } impl FileSink { /// Creates new file sink. /// Position is set to whatever position file has. pub fn new(file: &File) -> Self { let mut owned_file = file.try_cl...
FileSink
identifier_name
io.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...
#[test] fn test_io_read_over_limit() { let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); // Read all bytes from source src.read(&mut vec![0; 128]).unwrap(); assert_eq!(src.pos(), 4); // Try reading again, should return 0 bytes. let bytes_read = src.read(&mut ...
{ let mut src = FileSource::new(&get_test_file("alltypes_plain.parquet"), 0, 4); src.read(&mut vec![0; 1]).unwrap(); assert_eq!(src.pos(), 1); src.read(&mut vec![0; 4]).unwrap(); assert_eq!(src.pos(), 4); }
identifier_body
io.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...
res } } impl<R: ParquetReader> Position for FileSource<R> { fn pos(&self) -> u64 { self.start } } /// Struct that represents `File` output stream with position tracking. /// Used as a sink in file writer. pub struct FileSink { buf: BufWriter<File>, // This is not necessarily position in the underlying f...
{ self.start += bytes_read as u64; }
conditional_block
io.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...
/// position before any read. /// /// This is workaround and alternative for `file.try_clone()` method. It clones `File` /// while preserving independent position, which is not available with `try_clone()`. /// /// Designed after `arrow::io::RandomAccessFile`. pub struct FileSource<R: ParquetReader> { reader: Mutex<B...
random_line_split
entry.rs
use arch::mm::phys::Frame; use arch::mm::MappedAddr; use arch::mm::PhysAddr; use kernel::mm::*; bitflags! { pub struct Entry: usize { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; const USER = 1 << 2; const WRT_THROUGH = 1 << 3; const NO_CACHE ...
pub fn clear(&mut self) { self.bits = 0; } pub fn raw(&self) -> usize { self.bits } pub fn set_raw(&mut self, bits: usize) { self.bits = bits; } pub fn is_unused(&self) -> bool { self.bits == 0 } pub fn address(&self) -> PhysAddr { PhysAd...
{ Entry { bits: addr.read::<usize>(), } }
identifier_body
entry.rs
use arch::mm::phys::Frame; use arch::mm::MappedAddr; use arch::mm::PhysAddr; use kernel::mm::*; bitflags! { pub struct Entry: usize { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; const USER = 1 << 2; const WRT_THROUGH = 1 << 3; const NO_CACHE ...
(&mut self, bits: usize) { self.bits = bits; } pub fn is_unused(&self) -> bool { self.bits == 0 } pub fn address(&self) -> PhysAddr { PhysAddr(self.bits) & PhysAddr(0x000fffff_fffff000) } pub fn frame(&self) -> Option<Frame> { if self.contains(Entry::PRESENT) {...
set_raw
identifier_name
entry.rs
use arch::mm::phys::Frame; use arch::mm::MappedAddr; use arch::mm::PhysAddr; use kernel::mm::*; bitflags! { pub struct Entry: usize { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; const USER = 1 << 2; const WRT_THROUGH = 1 << 3; const NO_CACHE ...
self.bits = frame.address().0; } pub fn set_flags(&mut self, flags: Entry) { self.insert(flags | Entry::USER); } }
pub fn set_frame(&mut self, frame: &Frame) {
random_line_split
entry.rs
use arch::mm::phys::Frame; use arch::mm::MappedAddr; use arch::mm::PhysAddr; use kernel::mm::*; bitflags! { pub struct Entry: usize { const PRESENT = 1 << 0; const WRITABLE = 1 << 1; const USER = 1 << 2; const WRT_THROUGH = 1 << 3; const NO_CACHE ...
if flags.contains(virt::PageFlags::WRITABLE) { res.insert(Entry::WRITABLE); } return res; } pub unsafe fn from_addr(addr: MappedAddr) -> Entry { Entry { bits: addr.read::<usize>(), } } pub fn clear(&mut self) { self.bits = 0; ...
{ res.insert(Entry::USER); }
conditional_block
int.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 ...
if base == 0 { return 0; } let mut my_pow = exponent; let mut acc = 1; let mut multiplier = base; while(my_pow > 0u) { if my_pow % 2u == 1u { acc *= multiplier; } my_pow /= 2u; multiplier *= multiplier; ...
{ //Not mathemtically true if ~[base == 0] return 1; }
conditional_block
int.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. //! Operations and constants for `int` pub use self::inst::pow; mod inst { use num::{Primitive, BitCount}; pub type T = int; pub static bit...
random_line_split
int.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 ...
(&self) -> int { (*self as i64).trailing_zeros() as int } } /// Returns `base` raised to the power of `exponent` pub fn pow(base: int, exponent: uint) -> int { if exponent == 0u { //Not mathemtically true if ~[base == 0] return 1; } if base == 0 { return 0; }...
trailing_zeros
identifier_name
int.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 ...
#[test] fn test_overflows() { assert!((::int::max_value > 0)); assert!((::int::min_value <= 0)); assert!((::int::min_value + ::int::max_value + 1 == 0)); } }
{ assert!((pow(0, 0u) == 1)); assert!((pow(0, 1u) == 0)); assert!((pow(0, 2u) == 0)); assert!((pow(-1, 0u) == 1)); assert!((pow(1, 0u) == 1)); assert!((pow(-3, 2u) == 9)); assert!((pow(-3, 3u) == -27)); assert!((pow(4, 9u) == 262144)); }
identifier_body
custom_entities.rs
//! This example demonstrate how custom entities can be extracted from the DOCTYPE!, //! and later use to decode text and attribute values. //! //! NB: this example is deliberately kept simple:
//! * it only handles internal entities; //! * the regex in this example is simple but brittle; //! * it does not support the use of entities in entity declaration. extern crate quick_xml; extern crate regex; use quick_xml::events::Event; use quick_xml::Reader; use regex::bytes::Regex; use std::collections::HashMap; ...
//! * it assumes that the XML file is UTF-8 encoded (custom_entities must only contain UTF-8 data)
random_line_split
custom_entities.rs
//! This example demonstrate how custom entities can be extracted from the DOCTYPE!, //! and later use to decode text and attribute values. //! //! NB: this example is deliberately kept simple: //! * it assumes that the XML file is UTF-8 encoded (custom_entities must only contain UTF-8 data) //! * it only handles inter...
() -> Result<(), Box<dyn std::error::Error>> { let mut reader = Reader::from_str(DATA); reader.trim_text(true); let mut buf = Vec::new(); let mut custom_entities = HashMap::new(); let entity_re = Regex::new(r#"<!ENTITY\s+([^ \t\r\n]+)\s+"([^"]*)"\s*>"#)?; loop { match reader.read_event...
main
identifier_name
custom_entities.rs
//! This example demonstrate how custom entities can be extracted from the DOCTYPE!, //! and later use to decode text and attribute values. //! //! NB: this example is deliberately kept simple: //! * it assumes that the XML file is UTF-8 encoded (custom_entities must only contain UTF-8 data) //! * it only handles inter...
.unwrap() .unescape_and_decode_value_with_custom_entities( &reader, &custom_entities ) .unwrap()) .collect::<Vec<_>>() ...
{ let mut reader = Reader::from_str(DATA); reader.trim_text(true); let mut buf = Vec::new(); let mut custom_entities = HashMap::new(); let entity_re = Regex::new(r#"<!ENTITY\s+([^ \t\r\n]+)\s+"([^"]*)"\s*>"#)?; loop { match reader.read_event(&mut buf) { Ok(Event::DocType(re...
identifier_body
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/. */ #![cfg_attr(not(target_os = "windows"), feature(alloc_jemalloc))] #![feature(box_syntax)] #![feature(iter_arith)] ...
pub mod time; pub mod trace_dump;
random_line_split
context.rs
dump statistics about the style system. pub dump_style_statistics: bool, /// The minimum number of elements that must be traversed to trigger a dump /// of style statistics. pub style_statistics_threshold: usize, } #[cfg(feature = "gecko")] fn get_env_bool(name: &str) -> bool { use std::env; m...
/// A map with our snapshots in order to handle restyle hints. pub snapshot_map: &'a SnapshotMap, /// The animations that are currently running. #[cfg(feature = "servo")] pub running_animations: Arc<RwLock<FxHashMap<OpaqueNode, Vec<Animation>>>>, /// The list of animations that have expired si...
pub timer: Timer, /// Flags controlling how we traverse the tree. pub traversal_flags: TraversalFlags,
random_line_split
context.rs
statistics about the style system. pub dump_style_statistics: bool, /// The minimum number of elements that must be traversed to trigger a dump /// of style statistics. pub style_statistics_threshold: usize, } #[cfg(feature = "gecko")] fn get_env_bool(name: &str) -> bool { use std::env; match ...
(stack_size_limit: usize) -> Self { StackLimitChecker { lower_limit: StackLimitChecker::get_sp() - stack_size_limit, } } /// Checks whether the previously stored stack limit has now been exceeded. #[inline(never)] pub fn limit_exceeded(&self) -> bool { let curr_sp = ...
new
identifier_name
context.rs
statistics about the style system. pub dump_style_statistics: bool, /// The minimum number of elements that must be traversed to trigger a dump /// of style statistics. pub style_statistics_threshold: usize, } #[cfg(feature = "gecko")] fn get_env_bool(name: &str) -> bool { use std::env; match ...
, #[cfg(feature = "gecko")] PostAnimation { el, tasks } => { el.process_post_animation(tasks); }, } } /// Creates a task to update various animation-related state on a given /// (pseudo-)element. #[cfg(feature = "gecko")] pub fn update_ani...
{ el.update_animations(before_change_style, tasks); }
conditional_block
cards.rs
//! This module represents a basic, rule-agnostic 32-cards system. use rand::{thread_rng, IsaacRng, Rng, SeedableRng}; use std::num::Wrapping; use std::str::FromStr; use std::string::ToString; /// One of the four Suits: Heart, Spade, Diamond, Club. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)] #[re...
`card` from `self`. /// /// No effect if `self` does not contains `card`. pub fn remove(&mut self, card: Card) { self.0 &=!card.0; } /// Remove all cards from `self`. pub fn clean(&mut self) { *self = Hand::new(); } /// Returns `true` if `self` contains `card`. pub ...
= card.0; self } /// Removes
identifier_body
cards.rs
//! This module represents a basic, rule-agnostic 32-cards system. use rand::{thread_rng, IsaacRng, Rng, SeedableRng}; use std::num::Wrapping; use std::str::FromStr; use std::string::ToString; /// One of the four Suits: Heart, Spade, Diamond, Club. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)] #[re...
} } impl ToString for Deck { fn to_string(&self) -> String { let mut s = "[".to_owned(); for c in &self.cards { s += &c.to_string(); s += ","; } s + "]" } } #[cfg(test)] mod tests { use super::*; #[test] fn test_cards() { for i...
}
random_line_split
cards.rs
//! This module represents a basic, rule-agnostic 32-cards system. use rand::{thread_rng, IsaacRng, Rng, SeedableRng}; use std::num::Wrapping; use std::str::FromStr; use std::string::ToString; /// One of the four Suits: Heart, Spade, Diamond, Club. #[derive(PartialEq, Clone, Copy, Debug, Serialize, Deserialize)] #[re...
{ let mut s = "[".to_owned(); for c in &(*self).list() { s += &c.to_string(); s += ","; } s + "]" } } /// A deck of cards. pub struct Deck { cards: Vec<Card>, } impl Default for Deck { fn default() -> Self { Deck::new() } } impl Deck {...
> String
identifier_name
integration_tests.rs
use std::env; use std::process::Command; use std::str; pub fn bin_dir() -> String { let mut path = env::current_exe().unwrap(); path.pop(); if path.ends_with("deps") { path.pop(); } path.join("gb-rust-frontend").to_str().unwrap().to_string() } pub fn gekkio_test_rom(name: &str, timeout: us...
} #[test] pub fn blargg_cpu_instrs() { blargg_test_rom( "cpu_instrs", "cpu_instrs\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09:ok 10:ok 11:ok \n\nPassed all tests\n", 30, ); } #[test] pub fn blargg_halt_bug() { // TODO: blargg_test_rom_with_address( ...
0xA004, 2, );
random_line_split
integration_tests.rs
use std::env; use std::process::Command; use std::str; pub fn bin_dir() -> String { let mut path = env::current_exe().unwrap(); path.pop(); if path.ends_with("deps") { path.pop(); } path.join("gb-rust-frontend").to_str().unwrap().to_string() } pub fn gekkio_test_rom(name: &str, timeout: us...
() { blargg_test_rom_with_address( "mem_timing", "mem_timing\n\n01:ok 02:ok 03:ok \n\nPassed\n", 0xA004, 2, ); } #[test] pub fn blargg_cpu_instrs() { blargg_test_rom( "cpu_instrs", "cpu_instrs\n\n01:ok 02:ok 03:ok 04:ok 05:ok 06:ok 07:ok 08:ok \ 09...
blargg_mem_timing_2
identifier_name
integration_tests.rs
use std::env; use std::process::Command; use std::str; pub fn bin_dir() -> String { let mut path = env::current_exe().unwrap(); path.pop(); if path.ends_with("deps")
path.join("gb-rust-frontend").to_str().unwrap().to_string() } pub fn gekkio_test_rom(name: &str, timeout: usize) { let test_rom = "tests/gekkio/".to_owned() + name + ".gb"; let output = Command::new(bin_dir()) .args(&[&test_rom, "--headless", "--timeout", &timeout.to_string()]) .output() ...
{ path.pop(); }
conditional_block
integration_tests.rs
use std::env; use std::process::Command; use std::str; pub fn bin_dir() -> String { let mut path = env::current_exe().unwrap(); path.pop(); if path.ends_with("deps") { path.pop(); } path.join("gb-rust-frontend").to_str().unwrap().to_string() } pub fn gekkio_test_rom(name: &str, timeout: us...
{ gekkio_test_rom("acceptance/di_timing-GS", 1); }
identifier_body
check.rs
use std::error::Error; use std::fmt::{self, Debug, Display}; use futures::future::BoxFuture; use crate::client::Context; use crate::framework::standard::{Args, CommandOptions}; use crate::model::channel::Message; /// This type describes why a check has failed. /// /// **Note**: /// The bot-developer is supposed to p...
} impl PartialEq for Check { fn eq(&self, other: &Self) -> bool { self.name == other.name } }
}, } }
random_line_split
check.rs
use std::error::Error; use std::fmt::{self, Debug, Display}; use futures::future::BoxFuture; use crate::client::Context; use crate::framework::standard::{Args, CommandOptions}; use crate::model::channel::Message; /// This type describes why a check has failed. /// /// **Note**: /// The bot-developer is supposed to p...
{ /// No information on the failure. Unknown, /// Information dedicated to the user. User(String), /// Information purely for logging purposes. Log(String), /// Information for the user but also for logging purposes. UserAndLog { user: String, log: String }, } impl Error for Reason {} ...
Reason
identifier_name
check.rs
use std::error::Error; use std::fmt::{self, Debug, Display}; use futures::future::BoxFuture; use crate::client::Context; use crate::framework::standard::{Args, CommandOptions}; use crate::model::channel::Message; /// This type describes why a check has failed. /// /// **Note**: /// The bot-developer is supposed to p...
, } } } impl PartialEq for Check { fn eq(&self, other: &Self) -> bool { self.name == other.name } }
{ write!(f, "UserAndLog {{user: {}, log: {}}}", user, log) }
conditional_block
blockdev.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/. // Code to handle a single block device. use std::fs::OpenOptions; use std::path::PathBuf; use chrono::{DateTime, T...
#[derive(Debug)] pub struct StratBlockDev { dev: Device, pub(super) devnode: PathBuf, bda: BDA, used: RangeAllocator, user_info: Option<String>, hardware_info: Option<String>, dbus_path: MaybeDbusPath, } impl StratBlockDev { /// Make a new BlockDev from the parameters. /// Allocate ...
random_line_split
blockdev.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/. // Code to handle a single block device. use std::fs::OpenOptions; use std::path::PathBuf; use chrono::{DateTime, T...
/// The device's pool's UUID. #[allow(dead_code)] pub fn pool_uuid(&self) -> PoolUuid { self.bda.pool_uuid() } /// Last time metadata was written to this device. #[allow(dead_code)] pub fn last_update_time(&self) -> Option<&DateTime<Utc>> { self.bda.last_update_time() ...
{ self.bda.dev_uuid() }
identifier_body
blockdev.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/. // Code to handle a single block device. use std::fs::OpenOptions; use std::path::PathBuf; use chrono::{DateTime, T...
(&self) -> Sectors { self.used.available() } /// The maximum size of variable length metadata that can be accommodated. /// self.max_metadata_size() < self.metadata_size() pub fn max_metadata_size(&self) -> Sectors { self.bda.max_data_size() } /// Set the user info on this bloc...
available
identifier_name
blockdev.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/. // Code to handle a single block device. use std::fs::OpenOptions; use std::path::PathBuf; use chrono::{DateTime, T...
else { BlockDevState::NotInUse } } fn set_dbus_path(&mut self, path: MaybeDbusPath) { self.dbus_path = path } fn get_dbus_path(&self) -> &MaybeDbusPath { &self.dbus_path } } impl Recordable<BaseBlockDevSave> for StratBlockDev { fn record(&self) -> BaseBloc...
{ BlockDevState::InUse }
conditional_block
ancient_import.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(engine: Arc<EthEngine>, start_verifier: Box<EpochVerifier<EthereumMachine>>) -> Self { AncientVerifier { cur_verifier: RwLock::new(start_verifier), engine: engine, } } /// Verify the next block header, randomly choosing whether to do heavy or light /// verification. If the block is the end of an epoch, u...
new
identifier_name
ancient_import.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Verify the next block header, randomly choosing whether to do heavy or light /// verification. If the block is the end of an epoch, updates the epoch verifier. pub fn verify<R: Rng>( &self, rng: &mut R, header: &Header, chain: &BlockChain, ) -> Result<(), ::error::Error> { match rng.gen::<f32>() <= ...
{ AncientVerifier { cur_verifier: RwLock::new(start_verifier), engine: engine, } }
identifier_body
ancient_import.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
header: &Header, chain: &BlockChain, ) -> Result<(), ::error::Error> { match rng.gen::<f32>() <= HEAVY_VERIFY_RATE { true => self.cur_verifier.read().verify_heavy(header)?, false => self.cur_verifier.read().verify_light(header)?, } // ancient import will only use transitions obtained from the snapshot...
pub fn verify<R: Rng>( &self, rng: &mut R,
random_line_split
ancient_import.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
Ok(()) } }
{ let v = self.engine.epoch_verifier(&header, &transition.proof).known_confirmed()?; *self.cur_verifier.write() = v; }
conditional_block
http_ece.rs
use ece::encrypt; use crate::error::WebPushError; use crate::message::WebPushPayload; use crate::vapid::VapidSignature; /// Content encoding profiles. pub enum ContentEncoding { //Make sure this enum remains exhaustive as that allows for easier migrations to new versions. Aes128Gcm, } /// Struct for handling...
//Add more encoding standards to this match as they are created. match self.encoding { ContentEncoding::Aes128Gcm => { let result = encrypt(self.peer_public_key, self.peer_secret, content); let mut headers = Vec::new(); //VAPID uses a speci...
{ return Err(WebPushError::PayloadTooLarge); }
conditional_block
http_ece.rs
use ece::encrypt; use crate::error::WebPushError; use crate::message::WebPushPayload; use crate::vapid::VapidSignature; /// Content encoding profiles. pub enum ContentEncoding { //Make sure this enum remains exhaustive as that allows for easier migrations to new versions. Aes128Gcm, } /// Struct for handling...
(vapid_signature: Option<VapidSignature>, encoding: ContentEncoding) -> WebPushPayload { let p256dh = base64::decode_config( "BLMbF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_...
setup_payload
identifier_name
http_ece.rs
use ece::encrypt; use crate::error::WebPushError; use crate::message::WebPushPayload; use crate::vapid::VapidSignature; /// Content encoding profiles. pub enum ContentEncoding { //Make sure this enum remains exhaustive as that allows for easier migrations to new versions. Aes128Gcm, } /// Struct for handling...
#[test] fn test_aes128gcm_headers_no_vapid() { let wp_payload = setup_payload(None, ContentEncoding::Aes128Gcm); assert_eq!(wp_payload.crypto_headers.len(), 0); } #[test] fn test_aes128gcm_headers_vapid() { let auth_re = Regex::new(r"vapid t=(?P<sig_t>[^,]*), k=(?P<sig_k>[...
{ let p256dh = base64::decode_config( "BLMbF9ffKBiWQLCKvTHb6LO8Nb6dcUh6TItC455vu2kElga6PQvUmaFyCdykxY2nOSSL3yKgfbmFLRTUaGv4yV8", URL_SAFE, ) .unwrap(); let auth = base64::decode_config("xS03Fi5ErfTNH_l9WHE9Ig", URL_SAFE).unwrap(); let http_ece = HttpEce::...
identifier_body
http_ece.rs
use ece::encrypt; use crate::error::WebPushError; use crate::message::WebPushPayload; use crate::vapid::VapidSignature; /// Content encoding profiles. pub enum ContentEncoding { //Make sure this enum remains exhaustive as that allows for easier migrations to new versions. Aes128Gcm, } /// Struct for handling...
match self.encoding { ContentEncoding::Aes128Gcm => { let result = encrypt(self.peer_public_key, self.peer_secret, content); let mut headers = Vec::new(); //VAPID uses a special Authorisation header, which contains a ecdhsa key and a jwt. ...
if content.len() > 3052 { return Err(WebPushError::PayloadTooLarge); } //Add more encoding standards to this match as they are created.
random_line_split
char.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...
mut self) -> Option<char> { match self.state { EscapeDefaultState::Backslash(c) => { self.state = EscapeDefaultState::Char(c); Some('\\') } EscapeDefaultState::Char(c) => { self.state = EscapeDefaultState::Done; ...
xt(&
identifier_name
char.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...
EscapeUnicodeState::LeftBrace => { let mut n = 0; while (self.c as u32) >> (4 * (n + 1))!= 0 { n += 1; } self.state = EscapeUnicodeState::Value(n); Some('{') } EscapeUnicodeState::Value...
self.state = EscapeUnicodeState::LeftBrace; Some('u') }
conditional_block
char.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...
const TAG_CONT: u8 = 0b1000_0000; const TAG_TWO_B: u8 = 0b1100_0000; const TAG_THREE_B: u8 = 0b1110_0000; const TAG_FOUR_B: u8 = 0b1111_0000; const MAX_ONE_B: u32 = 0x80; const MAX_TWO_B: u32 = 0x800; const MAX_THREE_B: u32 = 0x10000; /* Lu Uppercase_Letter an uppercase letter Ll Low...
// UTF-8 ranges and tags for encoding characters
random_line_split
char.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...
#[inline] fn to_digit(self, radix: u32) -> Option<u32> { if radix > 36 { panic!("to_digit: radix is too high (maximum 36)"); } let val = match self { '0'... '9' => self as u32 - '0' as u32, 'a'... 'z' => self as u32 - 'a' as u32 + 10, 'A'... 'Z' ...
self.to_digit(radix).is_some() }
identifier_body
spoticli.rs
extern crate spotify; use spotify::{Spotify, SpotifyError}; use std::{thread, time}; fn main() { let spotify = match Spotify::connect() { Ok(result) => result, Err(error) => { match error { SpotifyError::ClientNotRunning => { println!("The Spotify Cli...
std::process::exit(3); } } } }; let reactor = spotify.poll(|client, status, change| { if change.client_version { println!("Spotify Client (Version {})", status.version()); } if change.track { println!("Now pl...
println!("The SpotifyWebHelper process is not running!"); std::process::exit(2); } SpotifyError::InternalError(err) => { println!("Internal Error: {:?}", err);
random_line_split
spoticli.rs
extern crate spotify; use spotify::{Spotify, SpotifyError}; use std::{thread, time}; fn main()
let reactor = spotify.poll(|client, status, change| { if change.client_version { println!("Spotify Client (Version {})", status.version()); } if change.track { println!("Now playing: {:#}", status.track()); println!("{}", status.full_track().track.uri); ...
{ let spotify = match Spotify::connect() { Ok(result) => result, Err(error) => { match error { SpotifyError::ClientNotRunning => { println!("The Spotify Client is not running!"); std::process::exit(1); } ...
identifier_body
spoticli.rs
extern crate spotify; use spotify::{Spotify, SpotifyError}; use std::{thread, time}; fn
() { let spotify = match Spotify::connect() { Ok(result) => result, Err(error) => { match error { SpotifyError::ClientNotRunning => { println!("The Spotify Client is not running!"); std::process::exit(1); } ...
main
identifier_name
lib.rs
#![allow(bad_style)] extern crate libc; /* automatically generated by rust-bindgen */ pub enum Struct_blip_t { } pub type blip_t = Struct_blip_t; pub type Enum_Unnamed1 = ::libc::c_uint; pub const blip_max_ratio: ::libc::c_uint = 1048576; pub type Enum_Unnamed2 = ::libc::c_uint; pub const blip_max_frame: ::libc::c_u...
pub fn blip_end_frame(arg1: *mut blip_t, clock_duration: ::libc::c_uint) -> (); pub fn blip_samples_avail(arg1: *const blip_t) -> ::libc::c_int; pub fn blip_read_samples(arg1: *mut blip_t, out: *mut ::libc::c_short, count: ::libc::c_int, stereo: ::libc::c_int) -> ::lib...
random_line_split
lib.rs
#![allow(bad_style)] extern crate libc; /* automatically generated by rust-bindgen */ pub enum
{ } pub type blip_t = Struct_blip_t; pub type Enum_Unnamed1 = ::libc::c_uint; pub const blip_max_ratio: ::libc::c_uint = 1048576; pub type Enum_Unnamed2 = ::libc::c_uint; pub const blip_max_frame: ::libc::c_uint = 4000; pub type blip_buffer_t = blip_t; extern "C" { pub fn blip_new(sample_count: ::libc::c_int) -> *...
Struct_blip_t
identifier_name
traits.rs
use {Vec2, Vec3, Vec4, Mat2, Mat3, Mat4, Quaternion}; use std::ops::{Add, Sub, Mul, Div}; use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign}; use std::ops::{Neg}; use std::cmp::{PartialEq, PartialOrd}; /// Allows us to be generic over numeric types in vectors pub trait Number: Add<Output = Self> + Sub<Ou...
impl Float for f32 { $(#[inline(always)] fn $fn(self) -> Self { self.$fn() })* #[inline(always)] fn sin_cos(self) -> (Self, Self) { self.sin_cos() } #[inline(always)] fn atan2(self, other: Self) -> Self { self.atan2(other) } } impl Flo...
$(fn $fn(self) -> Self;)* fn sin_cos(self) -> (Self, Self); fn atan2(self, other: Self) -> Self; }
random_line_split
traits.rs
use {Vec2, Vec3, Vec4, Mat2, Mat3, Mat4, Quaternion}; use std::ops::{Add, Sub, Mul, Div}; use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign}; use std::ops::{Neg}; use std::cmp::{PartialEq, PartialOrd}; /// Allows us to be generic over numeric types in vectors pub trait Number: Add<Output = Self> + Sub<O...
else { self } } } macro_rules! impl_number { ($type: ident, $one: expr, $zero: expr) => { impl Number for $type { const ONE: Self = $one; const ZERO: Self = $zero; } }; } impl_number!(i8, 1, 0); impl_number!(i16, 1, 0); impl_number!(i32, 1, 0);...
{ -self }
conditional_block
traits.rs
use {Vec2, Vec3, Vec4, Mat2, Mat3, Mat4, Quaternion}; use std::ops::{Add, Sub, Mul, Div}; use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign}; use std::ops::{Neg}; use std::cmp::{PartialEq, PartialOrd}; /// Allows us to be generic over numeric types in vectors pub trait Number: Add<Output = Self> + Sub<O...
} macro_rules! impl_number { ($type: ident, $one: expr, $zero: expr) => { impl Number for $type { const ONE: Self = $one; const ZERO: Self = $zero; } }; } impl_number!(i8, 1, 0); impl_number!(i16, 1, 0); impl_number!(i32, 1, 0); impl_number!(i64, 1, 0); impl_number!(u...
{ if self < Self::ZERO { -self } else { self } }
identifier_body
traits.rs
use {Vec2, Vec3, Vec4, Mat2, Mat3, Mat4, Quaternion}; use std::ops::{Add, Sub, Mul, Div}; use std::ops::{AddAssign, SubAssign, MulAssign, DivAssign}; use std::ops::{Neg}; use std::cmp::{PartialEq, PartialOrd}; /// Allows us to be generic over numeric types in vectors pub trait Number: Add<Output = Self> + Sub<O...
(self, step: f32) -> Self { (self / step).round() * step } } impl Round for f64 { fn round(self) -> Self { f64::round(self) } fn round_to_precision(self, precision: usize) -> Self { let s = 10f64.powi(precision as i32); (self * s).round() / s } type Step = f6...
round_to_step
identifier_name
uievent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
}
{ self.event.IsTrusted() }
identifier_body
uievent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
() -> UIEvent { UIEvent { event: Event::new_inherited(), view: Default::default(), detail: Cell::new(0), } } pub fn new_uninitialized(window: &Window) -> Root<UIEvent> { reflect_dom_object(box UIEvent::new_inherited(), windo...
new_inherited
identifier_name
uievent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
event.init_event(Atom::from(type_), can_bubble, cancelable); self.view.set(view); self.detail.set(detail); } // https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.event.IsTrusted() } }
{ return; }
conditional_block
uievent.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 dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::UIEventBin...
fn GetView(&self) -> Option<Root<Window>> { self.view.get() } // https://w3c.github.io/uievents/#widl-UIEvent-detail fn Detail(&self) -> i32 { self.detail.get() } // https://w3c.github.io/uievents/#widl-UIEvent-initUIEvent fn InitUIEvent(&self, type_: DOM...
} } impl UIEventMethods for UIEvent { // https://w3c.github.io/uievents/#widl-UIEvent-view
random_line_split
cfixed_string.rs
use std::borrow::{Borrow, Cow}; use std::ffi::{CStr, CString}; use std::fmt; use std::mem; use std::ops; use std::os::raw::c_char; use std::ptr; const STRING_SIZE: usize = 512; /// This is a C String abstractions that presents a CStr like /// interface for interop purposes but tries to be little nicer /// by avoiding...
CFixedString::Heap { ref s, len } => { str::from_utf8_unchecked(slice::from_raw_parts(s.as_ptr() as *const u8, len)) } } } } impl<'a> From<&'a str> for CFixedString { fn from(s: &'a str) -> Self { use std::fmt::Write; let mut string = CFixedStri...
{ str::from_utf8_unchecked(slice::from_raw_parts(s.as_ptr() as *const u8, len)) }
conditional_block