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
struct Lexer<'a> { src: &'a [u8], pos: usize } impl<'a> Lexer<'a> { fn new(src: &'a [u8]) -> Lexer { Lexer { src: src, pos: 0 } } } impl<'a> Lexer<'a> { fn ch(&self) -> u8 { self.src[self.pos] } fn
(&self) -> bool { self.pos >= self.src.len() } fn skip_ws(&mut self) -> usize { let prev_pos = self.pos; while self.valid_ws() { self.pos += 1; } self.pos - prev_pos } fn string(&mut self) -> Option<String> { let mut tok = Vec::<u8>::new(); loop { if self.eof() { break } match self....
eof
identifier_name
lib.rs
struct Lexer<'a> { src: &'a [u8], pos: usize } impl<'a> Lexer<'a> { fn new(src: &'a [u8]) -> Lexer
} impl<'a> Lexer<'a> { fn ch(&self) -> u8 { self.src[self.pos] } fn eof(&self) -> bool { self.pos >= self.src.len() } fn skip_ws(&mut self) -> usize { let prev_pos = self.pos; while self.valid_ws() { self.pos += 1; } self.pos - prev_pos } fn string(&mut self) -> Option<String> { let mut tok...
{ Lexer { src: src, pos: 0 } }
identifier_body
lib.rs
struct Lexer<'a> { src: &'a [u8], pos: usize } impl<'a> Lexer<'a> { fn new(src: &'a [u8]) -> Lexer { Lexer { src: src, pos: 0 } } } impl<'a> Lexer<'a> { fn ch(&self) -> u8 { self.src[self.pos] } fn eof(&self) -> bool { self.pos >= self.src.len() } fn skip_ws(&mut self) -> usize { let prev_pos = sel...
match self.ch() { b' ' => break, b'\t' => break, b'\r' => break, b'\n' => break, b'"' => break, _ => () } tok.push(self.ch()); self.pos += 1; } match tok.len() { 0 => None, _ => Some(String::from_utf8(tok).unwrap()) } } fn quoted_string(&mut self) -> Option<Stri...
let mut tok = Vec::<u8>::new(); loop { if self.eof() { break }
random_line_split
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}",...
(source:&str)->Vec<u8>{ DecodeBytes(source.as_bytes()) } // Convert byte to base64 rep fn BaseIndex(index:u8) -> u8 { match index { 62 => {b'+'} 63 => {b'/'} 0..25 => { b'A' + index } 26..51 => { b'a' + index - 26 } _ => { b'0'...
DecodeStr
identifier_name
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}",...
} } // Some tests fn main() { let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"); ::Base64::Debug::PrintBytes(encoded); let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVy...
b'a'..b'z' => { 26 + source - b'a'} b'0'..b'9' => { 52 + source - b'0'} _ => { 0 } }
random_line_split
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}",...
// Convert base64 rep to byte fn BaseIndexToByte(source:u8)->u8{ match source { b'+' => { 62 } b'/' => { 63 } b'A'..b'Z' => { source - b'A'} b'a'..b'z' => { 26 + source - b'a'} b'0'..b'9' => { 52 + source - b'0'} _ => { 0 } ...
{ match index { 62 => {b'+'} 63 => {b'/'} 0..25 => { b'A' + index } 26..51 => { b'a' + index - 26 } _ => { b'0' + index - 52 } } }
identifier_body
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}",...
i += 3; } output } // Encode str pub fn EncodeStr(source: &str) -> Vec<u8> { EncodeBytes(source.as_bytes()) } // Decode array of u8 bytes pub fn DecodeBytes(source:&[u8]) -> Vec<u8> { let bytes = source; ...
{ output.push(BaseIndex(((bytes[i] & 0b11) << 4))); output.push(b'='); output.push(b'='); }
conditional_block
bitboard.rs
// use std::num::Int; pub type Bitboard = u32; pub trait BitMove { fn up_left(&self) -> Self; fn up_right(&self) -> Self; fn down_left(&self) -> Self; fn down_right(&self) -> Self; fn is(&self) -> bool; } pub const S: [Bitboard; 32] = [ 1 << 18, 1 << 12, 1 << 6, 1 << 0,
1 << 3, 1 << 29, 1 << 23, 1 << 17, 1 << 10, 1 << 4, 1 << 30, 1 << 24, 1 << 11, 1 << 05, 1 << 31, 1 << 25]; pub const BP_INIT: Bitboard = S[0] | S[1] | S[2] | S[3] | S[4] | S[5] | S[6] | S[7] | S[8] | S[9] | S[10] | S[11]; pub const WP_INIT: Bitboard =...
1 << 19, 1 << 13, 1 << 7, 1 << 1, 1 << 26, 1 << 20, 1 << 14, 1 << 8, 1 << 27, 1 << 21, 1 << 15, 1 << 9, 1 << 2, 1 << 28, 1 << 22, 1 << 16,
random_line_split
bitboard.rs
// use std::num::Int; pub type Bitboard = u32; pub trait BitMove { fn up_left(&self) -> Self; fn up_right(&self) -> Self; fn down_left(&self) -> Self; fn down_right(&self) -> Self; fn is(&self) -> bool; } pub const S: [Bitboard; 32] = [ 1 << 18, 1 << 12, 1 << 6, 1 << 0, ...
} // Maps from Bitboard indicating a position to the number // of that position itself pub fn bbumap(b: Bitboard) -> Bitboard { S.iter().position(|&x| x == b).unwrap() as u32 } #[inline] pub fn high_bit(mut board: Bitboard) -> Bitboard { board |= board >> 1; board |= board >> 2; board |= board >> 4; ...
{ *self != 0 }
identifier_body
bitboard.rs
// use std::num::Int; pub type Bitboard = u32; pub trait BitMove { fn up_left(&self) -> Self; fn up_right(&self) -> Self; fn down_left(&self) -> Self; fn down_right(&self) -> Self; fn is(&self) -> bool; } pub const S: [Bitboard; 32] = [ 1 << 18, 1 << 12, 1 << 6, 1 << 0, ...
(src: u16, dst: u16, jump: bool) -> Move { assert!(src < 32); assert!(dst < 32); Move { src: src, dst: dst, jump: jump, __dummy: () } } pub fn calc_direction(&self) -> Option<Direction> { let (src, dst) = (S[self.src as usize], S[self.dst as usize]); ...
new
identifier_name
lmcons.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! This file contains constants used throughout the LAN Manager API header files. pub const CNLEN: ::DWORD = 15; pub const LM20_CNLEN: ::DWORD = 15; pub const DNLEN: ::DWORD = CNLEN; pub const LM20_DNLEN: ::DWORD = LM20_CNLEN; pub const...
pub const PLATFORM_ID_NT: ::DWORD = 500; pub const PLATFORM_ID_OSF: ::DWORD = 600; pub const PLATFORM_ID_VMS: ::DWORD = 700;
pub type API_RET_TYPE = NET_API_STATUS; pub const PLATFORM_ID_DOS: ::DWORD = 300; pub const PLATFORM_ID_OS2: ::DWORD = 400;
random_line_split
lint-unused-imports.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 ...
(p: Point) -> int { return 2 * (p.x + p.y); } } #[allow(unused_imports)] mod foo { use std::cmp::Eq; } } fn main() { cal(foo::Point{x:3, y:9}); let mut a = 3; let mut b = 4; swap(&mut a, &mut b); test::C.b(); let _a = from_elem(0, 0); }
cc
identifier_name
lint-unused-imports.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 ...
// Make sure this import is warned about when at least one of its imported names // is unused use std::slice::{from_fn, from_elem}; //~ ERROR unused import mod test { pub trait A { fn a(&self) {} } pub trait B { fn b(&self) {} } pub struct C; impl A for C {} impl B for C {} } mod foo { pub s...
// counted as being used. use test::B;
random_line_split
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use cssparser::Parser; use st...
ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] Co...
PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero,
random_line_split
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use cssparser::Parser; use st...
() -> Self { Self { kind: SVGPaintKind::None, fallback: SVGPaintFallback::Unset, } } } /// An SVG paint value without the fallback. /// /// Whereas the spec only allows PaintServer to have a fallback, Gecko lets the /// context properties have a fallback as well. #[animation...
default
identifier_name
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use cssparser::Parser; use st...
let fallback = input .try(|i| SVGPaintFallback::parse(context, i)) .unwrap_or(SVGPaintFallback::Unset); Ok(SVGPaint { kind, fallback }) } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone, ComputeSquaredDistance, ...
{ return Ok(SVGPaint { kind, fallback: SVGPaintFallback::Unset, }); }
conditional_block
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); ...
() { let mut repl = REPL::new(); repl.test("if True then 1 else 0", Some("1")); repl.test("if False then 1 else 0", Some("0")); } #[test] fn records() { let mut repl = REPL::new(); repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None); repl.test("record.pi", Some("3.14")); repl.t...
if_expressions
identifier_name
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); ...
#[test] fn assert() { let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); repl.test("assert False", None); }
{ let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); }
identifier_body
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); ...
self.session.exp_string(self.prompt)?; Ok(()) } fn quit(&mut self) { self.quit_().unwrap_or_else(|err| panic!("{}", err)); } fn quit_(&mut self) -> Result<()> { let line: &'static str = ":q"; self.session.send_line(line)?; self.session.exp_string(line)?...
self.session.exp_string(string)?; }
random_line_split
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); ...
self.session.exp_string(self.prompt)?; Ok(()) } fn quit(&mut self) { self.quit_().unwrap_or_else(|err| panic!("{}", err)); } fn quit_(&mut self) -> Result<()> { let line: &'static str = ":q"; self.session.send_line(line)?; self.session.exp_string(line)...
{ self.session.exp_string(string)?; }
conditional_block
aspect_frame.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
use glib::translate::ToGlibPtr; use gtk::cast::GTK_ASPECTFRAME; use gtk::{self, ffi}; use glib::to_gboolean; /// AspectFrame — A frame that constrains its child to a particular aspect ratio struct_Widget!(AspectFrame); impl AspectFrame { pub fn new(label: Option<&str>, x_align: f32, y_align: f32, ratio: f32, obe...
use libc::c_float;
random_line_split
aspect_frame.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
mut self, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> () { unsafe { ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)); } ...
t(&
identifier_name
aspect_frame.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
pub fn set(&mut self, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> () { unsafe { ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)...
let tmp_pointer = unsafe { ffi::gtk_aspect_frame_new(label.borrow_to_glib().0, x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)) }; check_pointer!(tmp_pointer, AspectFrame) ...
identifier_body
util.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt; use std::str; // A struct that divide a name into serveral parts that meets rust's guidelines. struct NameSpliter<'a> { name: &'a [u8], pos: usize, } impl<'a> NameSpliter<'a> { fn new(s: &str) -> NameSpliter { NameSp...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match self { MethodType::Unary => "MethodType::Unary", MethodType::ClientStreaming => "MethodType::ClientStreaming", MethodType::ServerStreaming => "MethodType::S...
fmt
identifier_name
util.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt; use std::str; // A struct that divide a name into serveral parts that meets rust's guidelines. struct NameSpliter<'a> { name: &'a [u8], pos: usize, } impl<'a> NameSpliter<'a> { fn new(s: &str) -> NameSpliter { NameSp...
else if c == b'_' { pos = i; break; } else { meet_lower = true; if upper_len > 1 { // So it should be AAa pos = i - 1; break; } } } let s =...
{ if meet_lower { // So it should be AaA or aaA pos = i; break; } upper_len += 1; }
conditional_block
util.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt; use std::str; // A struct that divide a name into serveral parts that meets rust's guidelines. struct NameSpliter<'a> { name: &'a [u8], pos: usize, } impl<'a> NameSpliter<'a> { fn new(s: &str) -> NameSpliter { NameSp...
("async_request", "async_request"), ("createID", "create_id"), ("AsyncRClient", "async_r_client"), ("CreateIDForReq", "create_id_for_req"), ("Create_ID_For_Req", "create_id_for_req"), ("Create_ID_For__Req", "create_id_for_req"), ("ID", ...
#[test] fn test_snake_name() { let cases = vec![ ("AsyncRequest", "async_request"), ("asyncRequest", "async_request"),
random_line_split
expr.rs
#![allow(dead_code)] use super::*; use std::fmt; use std::sync::Arc; #[derive(Clone, Debug)] pub enum Expr { Nil, Bool(bool), Int(i64), Flt(f64), Str(String), Sym(Symbol), Func(Arc<Function>), Macro(Arc<Macro>), List(List), Vector(Vector), Map(Map), } impl Expr {
} else { None } } pub fn int(&self) -> Option<i64> { if let Expr::Int(x) = *self { Some(x) } else { None } } pub fn flt(&self) -> Option<f64> { if let Expr::Flt(x) = *self { Some(x) } else { ...
pub fn boolean(&self) -> Option<bool> { if let Expr::Bool(x) = *self { Some(x)
random_line_split
expr.rs
#![allow(dead_code)] use super::*; use std::fmt; use std::sync::Arc; #[derive(Clone, Debug)] pub enum Expr { Nil, Bool(bool), Int(i64), Flt(f64), Str(String), Sym(Symbol), Func(Arc<Function>), Macro(Arc<Macro>), List(List), Vector(Vector), Map(Map), } impl Expr { pub f...
pub fn is_flt(&self) -> bool { self.flt().is_some() } pub fn is_num(&self) -> bool { match *self { Expr::Flt(_) | Expr::Int(_) => true, _ => false, } } pub fn map_int<E, F>(self, f: F) -> Expr where F: FnOnce(i64) -> E, E: Into<...
{ self.int().is_some() }
identifier_body
expr.rs
#![allow(dead_code)] use super::*; use std::fmt; use std::sync::Arc; #[derive(Clone, Debug)] pub enum Expr { Nil, Bool(bool), Int(i64), Flt(f64), Str(String), Sym(Symbol), Func(Arc<Function>), Macro(Arc<Macro>), List(List), Vector(Vector), Map(Map), } impl Expr { pub f...
(&self) -> Option<&Vector> { if let Expr::Vector(ref x) = *self { Some(x) } else { None } } pub fn func(&self) -> Option<Arc<Function>> { if let Expr::Func(ref x) = *self { Some(x.clone()) } else { None } } ...
vector
identifier_name
astconv.rs
Some(a) => fmt!("lifetime %s", lifetime_to_str(a, tcx.sess.intr())) }; tcx.sess.span_err( span, fmt!("Illegal %s: %s", descr, e.msg)); e.replacement } } } pub fn ast_region_to_region<A...
pub static NO_REGIONS: uint = 1; pub static NO_TPS: uint = 2; // Parses the programmer's textual representation of a type into our // internal notion of a type. `getter` is a function that returns the type // corresponding to a definition ID: pub fn ast_ty_to_ty<AC:AstConv, RS:region_scope + Copy + Durable>( sel...
{ // Look up the polytype of the item and then substitute the provided types // for any type/region parameters. let ty::ty_param_substs_and_ty { substs: substs, ty: ty } = ast_path_to_substs_and_ty(self, rscope, did, path); ty_param_substs_and_ty { substs: substs, ty: ty } }
identifier_body
astconv.rs
( tcx: ty::ctxt, span: span, a_r: Option<@ast::Lifetime>, res: Result<ty::Region, RegionError>) -> ty::Region { match res { result::Ok(r) => r, result::Err(ref e) => { let descr = match a_r { None => ~"anonymous lifetime", Some(a) => fmt!("...
get_region_reporting_err
identifier_name
astconv.rs
Some(a) => fmt!("lifetime %s", lifetime_to_str(a, tcx.sess.intr())) }; tcx.sess.span_err( span, fmt!("Illegal %s: %s", descr, e.msg)); e.replacement } } } pub fn ast_region_to_region<A...
}; get_region_reporting_err(self.tcx(), span, opt_lifetime, res) } pub fn ast_path_to_substs_and_ty<AC:AstConv,RS:region_scope + Copy + Durable>( self: &AC, rscope: &RS, did: ast::def_id, path: @ast::path) -> ty_param_substs_and_ty { let tcx = self.tcx(); let ty::...
{ (lifetime.span, rscope.named_region(lifetime.span, lifetime.ident)) }
conditional_block
astconv.rs
* Note that the self region for the `foo` defaulted to `&` in the first * case but `&a` in the second. Basically, defaults that appear inside * an rptr (`&r.T`) use the region `r` that appears in the rptr. */ use core::prelude::*; use middle::const_eval; use middle::ty::{arg, substs}; use middle::ty::{ty_param_s...
* Case (b) says that if you have a type: * type foo<'self> = ...; * type bar = fn(&foo, &a.foo) * The fully expanded version of type bar is: * type bar = fn(&'foo &, &a.foo<'a>)
random_line_split
reporter.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crate::cpu::collector::{register_collector, Collector, CollectorHandle}; use crate::cpu::recorder::CpuRecords; use crate::Config; use std::fmt::{self, Display, Formatter}; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst;...
(scheduler: Scheduler<Task>) -> Self { Self { scheduler } } } impl Collector for CpuRecordsCollector { fn collect(&self, records: Arc<CpuRecords>) { self.scheduler.schedule(Task::CpuRecords(records)).ok(); } } pub enum Task { ConfigChange(Config), CpuRecords(Arc<CpuRecords>), } im...
new
identifier_name
reporter.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crate::cpu::collector::{register_collector, Collector, CollectorHandle}; use crate::cpu::recorder::CpuRecords; use crate::Config; use std::fmt::{self, Display, Formatter}; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst;...
} impl Runnable for ResourceMeteringReporter { type Task = Task; fn run(&mut self, task: Self::Task) { match task { Task::ConfigChange(new_config) => { let old_config_enabled = self.config.enabled; let old_config_agent_address = self.config.agent_address.cl...
{ let channel = { let cb = ChannelBuilder::new(self.env.clone()) .keepalive_time(Duration::from_secs(10)) .keepalive_timeout(Duration::from_secs(3)); cb.connect(&self.config.agent_address) }; self.client = Some(ResourceUsageAgentClient::new...
identifier_body
reporter.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crate::cpu::collector::{register_collector, Collector, CollectorHandle}; use crate::cpu::recorder::CpuRecords; use crate::Config; use std::fmt::{self, Display, Formatter}; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering::SeqCst;...
req.set_record_list_timestamp_sec(timestamp_list); req.set_record_list_cpu_time_ms(cpu_time_ms_list); if tx.send((req, WriteFlags::default())).await.is_err() { return; } ...
for (tag, (timestamp_list, cpu_time_ms_list, _)) in records { let mut req = CpuTimeRecord::default(); req.set_resource_group_tag(tag);
random_line_split
mod.rs
// This file is released under the same terms as Rust itself. pub mod github_status; pub mod jenkins; use config::PipelinesConfig; use hyper::Url; use pipeline::{GetPipelineId, PipelineId}; use vcs::Commit; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct CiId(pub i32); #[derive(Clone, Debug)] pub enum...
{ BuildStarted(CiId, Commit, Option<Url>), BuildSucceeded(CiId, Commit, Option<Url>), BuildFailed(CiId, Commit, Option<Url>), } impl GetPipelineId for Event { fn pipeline_id<C: PipelinesConfig +?Sized>(&self, config: &C) -> PipelineId { let ci_id = match *self { Event::BuildStarted...
Event
identifier_name
mod.rs
// This file is released under the same terms as Rust itself. pub mod github_status; pub mod jenkins; use config::PipelinesConfig; use hyper::Url; use pipeline::{GetPipelineId, PipelineId}; use vcs::Commit; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct CiId(pub i32); #[derive(Clone, Debug)] pub enum...
impl GetPipelineId for Event { fn pipeline_id<C: PipelinesConfig +?Sized>(&self, config: &C) -> PipelineId { let ci_id = match *self { Event::BuildStarted(i, _, _) => i, Event::BuildSucceeded(i, _, _) => i, Event::BuildFailed(i, _, _) => i, }; config.by_c...
BuildSucceeded(CiId, Commit, Option<Url>), BuildFailed(CiId, Commit, Option<Url>), }
random_line_split
arm.rs
//! Contains arm-specific types use core::convert::From; use core::{cmp, fmt, slice}; use capstone_sys::{ arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter, cs_arm_op__bindgen_ty_2}; use libc::c_uint; pub use crate::arch::arch_builder::arm::*; use crate::arch::DetailsArchInsn; use crate::instruction::{...
/// Vector size pub fn vector_size(&self) -> i32 { self.0.vector_size as i32 } /// Type of vector data pub fn vector_data(&self) -> ArmVectorData { self.0.vector_data } /// CPS mode for CPS instruction pub fn cps_mode(&self) -> ArmCPSMode { self.0.cps_mode ...
{ self.0.usermode }
identifier_body
arm.rs
//! Contains arm-specific types use core::convert::From; use core::{cmp, fmt, slice}; use capstone_sys::{ arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter, cs_arm_op__bindgen_ty_2};
use libc::c_uint; pub use crate::arch::arch_builder::arm::*; use crate::arch::DetailsArchInsn; use crate::instruction::{RegId, RegIdInt}; pub use capstone_sys::arm_insn_group as ArmInsnGroup; pub use capstone_sys::arm_insn as ArmInsn; pub use capstone_sys::arm_reg as ArmReg; pub use capstone_sys::arm_vectordata_type ...
random_line_split
arm.rs
//! Contains arm-specific types use core::convert::From; use core::{cmp, fmt, slice}; use capstone_sys::{ arm_op_mem, arm_op_type, cs_arm, cs_arm_op, arm_shifter, cs_arm_op__bindgen_ty_2}; use libc::c_uint; pub use crate::arch::arch_builder::arm::*; use crate::arch::DetailsArchInsn; use crate::instruction::{...
(&self) -> RegId { RegId(self.0.index as RegIdInt) } /// Scale for index register (can be 1, or -1) pub fn scale(&self) -> i32 { self.0.scale as i32 } /// Disp value pub fn disp(&self) -> i32 { self.0.disp as i32 } } impl_PartialEq_repr_fields!(ArmOpMem; base, ...
index
identifier_name
absurd_extreme_comparisons.rs
use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use clippy_utils::comparisons::{normalize_comparison, Rel}; use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint_...
}
random_line_split
absurd_extreme_comparisons.rs
use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use clippy_utils::comparisons::{normalize_comparison, Rel}; use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint_...
{ Minimum, Maximum, } struct ExtremeExpr<'a> { which: ExtremeType, expr: &'a Expr<'a>, } enum AbsurdComparisonResult { AlwaysFalse, AlwaysTrue, InequalityImpossible, } fn is_cast_between_fixed_and_target<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>) -> bool { if let ExprKind:...
ExtremeType
identifier_name
absurd_extreme_comparisons.rs
use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty; use rustc_session::{declare_lint_pass, declare_tool_lint}; use clippy_utils::comparisons::{normalize_comparison, Rel}; use clippy_utils::consts::{constant, Constant}; use clippy_utils::diagnostics::span_lint_...
fn detect_absurd_comparison<'tcx>( cx: &LateContext<'tcx>, op: BinOpKind, lhs: &'tcx Expr<'_>, rhs: &'tcx Expr<'_>, ) -> Option<(ExtremeExpr<'tcx>, AbsurdComparisonResult)> { use AbsurdComparisonResult::{AlwaysFalse, AlwaysTrue, InequalityImpossible}; use ExtremeType::{Maximum, Minimum}; /...
{ if let ExprKind::Cast(cast_exp, _) = expr.kind { let precast_ty = cx.typeck_results().expr_ty(cast_exp); let cast_ty = cx.typeck_results().expr_ty(expr); return is_isize_or_usize(precast_ty) != is_isize_or_usize(cast_ty); } false }
identifier_body
compress.rs
use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use ::image; use ::image::GenericImage; use dct; use quantize; use color_space; use compressed_image; use protobuf::Message;
use flate2::Compression; use flate2::write::ZlibEncoder; pub fn compress_file(input_filename: &Path) { let file_stem = match input_filename.file_stem() { Some(stem) => stem, None => panic!("Invalid input filename: Could not automatically determine output file"), }; let file_container ...
random_line_split
compress.rs
use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use ::image; use ::image::GenericImage; use dct; use quantize; use color_space; use compressed_image; use protobuf::Message; use flate2::Compression; use flate2::write::ZlibEncoder; pub fn compress_file(input_filename: &Path) { let file...
{ dct::dct2_2d(width, height, &mut uncompressed_channel_data); quantize::encode(width, height, &uncompressed_channel_data) }
identifier_body
compress.rs
use std::fs::File; use std::io::Write; use std::path::{Path, PathBuf}; use ::image; use ::image::GenericImage; use dct; use quantize; use color_space; use compressed_image; use protobuf::Message; use flate2::Compression; use flate2::write::ZlibEncoder; pub fn compress_file(input_filename: &Path) { let file...
(input_filename: &Path, output_filename: &Path) { if let Some(extension) = output_filename.extension() { assert!(extension == "msca", "Output file for compression must be'msca'") } else { panic!("Output file for compression must be msca") } let input_image = image:...
compress_file_to_output
identifier_name
config.rs
use crate::files; use crate::package; use std::path::PathBuf; use serde_json; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Serialize, Deserialize, Node)] pub struct Config { pub current_package: Option<String>, pub netplay_region: Option<String>, pub auto_save_replay: ...
} impl Config { fn get_path() -> PathBuf { let mut path = files::get_path(); path.push("config.json"); path } pub fn load() -> Config { if let Ok (json) = files::load_json(Config::get_path()) { if let Ok (mut config) = serde_json::from_value::<Config>(json) { ...
pub physical_device_name: Option<String>,
random_line_split
config.rs
use crate::files; use crate::package; use std::path::PathBuf; use serde_json; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Serialize, Deserialize, Node)] pub struct Config { pub current_package: Option<String>, pub netplay_region: Option<String>, pub auto_save_replay: ...
() -> Config { if let Ok (json) = files::load_json(Config::get_path()) { if let Ok (mut config) = serde_json::from_value::<Config>(json) { // current_package may have been deleted since config was last saved if let Some (ref current_package) = config.current_package.c...
load
identifier_name
config.rs
use crate::files; use crate::package; use std::path::PathBuf; use serde_json; use treeflection::{Node, NodeRunner, NodeToken}; #[derive(Clone, Serialize, Deserialize, Node)] pub struct Config { pub current_package: Option<String>, pub netplay_region: Option<String>, pub auto_save_replay: ...
warn!("{:?} is invalid or does not exist, loading default values", Config::get_path()); Config::default() } pub fn save(&self) { files::save_struct(Config::get_path(), self); } } impl Default for Config { fn default() -> Config { Config { current_package: ...
{ if let Ok (mut config) = serde_json::from_value::<Config>(json) { // current_package may have been deleted since config was last saved if let Some (ref current_package) = config.current_package.clone() { if !package::exists(current_package.as_str()) { ...
conditional_block
main.rs
extern crate llvm_sys as llvm; extern crate libc; extern crate itertools; #[macro_use] extern crate clap; extern crate uuid; extern crate toml; #[macro_use] extern crate serde_derive; extern crate serde; extern crate bincode; extern crate time; extern crate either; macro_rules! try_opt { ($e:expr) =>( matc...
() -> CompileResult<i32> { let app = clap_app!(cobrac => (version: "0.1") (author: "Joris Guisson <joris.guisson@gmail.com>") (about: "Nomad language compiler") (@arg DUMP: -d --dump +takes_value "Dump internal compiler state for debug purposes. Argument can be all, ast, bytecode or ...
run
identifier_name
main.rs
extern crate llvm_sys as llvm; extern crate libc; extern crate itertools; #[macro_use] extern crate clap; extern crate uuid; extern crate toml; #[macro_use] extern crate serde_derive; extern crate serde; extern crate bincode; extern crate time; extern crate either; macro_rules! try_opt { ($e:expr) =>( matc...
{ match run() { Ok(ret) => { llvm_shutdown(); exit(ret) }, Err(e) => { e.print(); llvm_shutdown(); exit(-1); }, } }
identifier_body
main.rs
extern crate llvm_sys as llvm; extern crate libc; extern crate itertools; #[macro_use] extern crate clap; extern crate uuid; extern crate toml; #[macro_use] extern crate serde_derive; extern crate serde; extern crate bincode; extern crate time; extern crate either; macro_rules! try_opt { ($e:expr) =>( matc...
build_command(matches, dump_flags) } else if let Some(matches) = matches.subcommand_matches("buildpkg") { build_package_command(matches, dump_flags) } else if let Some(matches) = matches.subcommand_matches("exports") { exports_command(matches) } else { println!("{}", matches....
} else if let Some(matches) = matches.subcommand_matches("build") {
random_line_split
compound2d.rs
extern crate nalgebra as na; use na::{Isometry2, Vector2}; use ncollide2d::shape::{Compound, Cuboid, ShapeHandle}; fn main() { // Delta transformation matrices. let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero()); let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero()); let...
// 2) Create the compound shape. let compound = Compound::new(shapes); assert!(compound.shapes().len() == 3) }
random_line_split
compound2d.rs
extern crate nalgebra as na; use na::{Isometry2, Vector2}; use ncollide2d::shape::{Compound, Cuboid, ShapeHandle}; fn main()
{ // Delta transformation matrices. let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero()); let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero()); let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero()); // 1) Initialize the shape list. let mut shapes = Vec...
identifier_body
compound2d.rs
extern crate nalgebra as na; use na::{Isometry2, Vector2}; use ncollide2d::shape::{Compound, Cuboid, ShapeHandle}; fn
() { // Delta transformation matrices. let delta1 = Isometry2::new(Vector2::new(0.0f32, -1.5), na::zero()); let delta2 = Isometry2::new(Vector2::new(-1.5f32, 0.0), na::zero()); let delta3 = Isometry2::new(Vector2::new(1.5f32, 0.0), na::zero()); // 1) Initialize the shape list. let mut shapes = ...
main
identifier_name
lib.rs
// Copyright TUNTAP, 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![allow(non_upper_case_globals)] #![allow(non_camel_case_types)] #![allow(non_snake_case)] use base::{ioctl_ior_nr, ioctl_iow_nr}; // genera...
ioctl_iow_nr!(TUNSETIFINDEX, TUNTAP, 218, ::std::os::raw::c_uint); ioctl_ior_nr!(TUNGETFILTER, TUNTAP, 219, sock_fprog); ioctl_iow_nr!(TUNSETVNETLE, TUNTAP, 220, ::std::os::raw::c_int); ioctl_ior_nr!(TUNGETVNETLE, TUNTAP, 221, ::std::os::raw::c_int); ioctl_iow_nr!(TUNSETVNETBE, TUNTAP, 222, ::std::os::raw::c_int); ioct...
ioctl_iow_nr!(TUNSETQUEUE, TUNTAP, 217, ::std::os::raw::c_int);
random_line_split
mod.rs
// Copyright (C) 2020 Sebastian Dröge <sebastian@centricular.com> // // 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...
// the name "rsrgb2gray" for being able to instantiate it via e.g. // gst::ElementFactory::make(). pub fn register(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), "rsrgb2gray", gst::Rank::None, Rgb2Gray::static_type(), ) }
// Registers the type for our element, and then registers in GStreamer under
random_line_split
mod.rs
// Copyright (C) 2020 Sebastian Dröge <sebastian@centricular.com> // // 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...
plugin: &gst::Plugin) -> Result<(), glib::BoolError> { gst::Element::register( Some(plugin), "rsrgb2gray", gst::Rank::None, Rgb2Gray::static_type(), ) }
egister(
identifier_name
mod.rs
// Copyright (C) 2020 Sebastian Dröge <sebastian@centricular.com> // // 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...
gst::Element::register( Some(plugin), "rsrgb2gray", gst::Rank::None, Rgb2Gray::static_type(), ) }
identifier_body
build.rs
use std::env; use std::fs::File; use std::io::Write; use std::path::Path; use std::process::Command; fn rustc_version()->String { let cmd = Command::new(env::var("RUSTC").unwrap()) .args(&["--version"]) .output() .expect("failed to execute process"); let mut x = Str...
x } fn pybuildinfo()->Vec<u8> { let pyscript = " import os import sys if __name__ == '__main__': path = os.path.abspath(os.path.join(os.getcwd(), '..')) sys.path.append(path) import pybuildinfo.cmd pybuildinfo.cmd.cmd(sys.argv[2:]) "; let dict = format!("-dict={}", format!("{{ \"b...
{ x = x[5..].trim().to_string(); }
conditional_block
build.rs
use std::env; use std::fs::File; use std::io::Write; use std::path::Path; use std::process::Command; fn rustc_version()->String
fn pybuildinfo()->Vec<u8> { let pyscript = " import os import sys if __name__ == '__main__': path = os.path.abspath(os.path.join(os.getcwd(), '..')) sys.path.append(path) import pybuildinfo.cmd pybuildinfo.cmd.cmd(sys.argv[2:]) "; let dict = format!("-dict={}", format!("{{ \"build_too...
{ let cmd = Command::new(env::var("RUSTC").unwrap()) .args(&["--version"]) .output() .expect("failed to execute process"); let mut x = String::from_utf8(cmd.stdout).unwrap(); x = x.trim().to_string(); if x.starts_with("rustc") { x = x[5..].trim().t...
identifier_body
build.rs
use std::env; use std::fs::File; use std::io::Write; use std::path::Path; use std::process::Command; fn rustc_version()->String { let cmd = Command::new(env::var("RUSTC").unwrap()) .args(&["--version"]) .output() .expect("failed to execute process"); let mut x = Str...
\"build_toolchain_version\": \"{}\", \"build_target\": \"{}\" }}", rustc_version(), env::var("TARGET").unwrap())); let cmd = Command::new("python") .args(&["-c", pyscript, "-vcs=\"..\"", "-template=buildinfo_template.rs", &dict]) .output() .expect("f...
pybuildinfo.cmd.cmd(sys.argv[2:]) "; let dict = format!("-dict={}", format!("{{ \"build_toolchain\": \"rustc\",
random_line_split
build.rs
use std::env; use std::fs::File; use std::io::Write; use std::path::Path; use std::process::Command; fn
()->String { let cmd = Command::new(env::var("RUSTC").unwrap()) .args(&["--version"]) .output() .expect("failed to execute process"); let mut x = String::from_utf8(cmd.stdout).unwrap(); x = x.trim().to_string(); if x.starts_with("rustc") { x = x[5..]....
rustc_version
identifier_name
mod.rs
use syntax::ptr::P; use syntax::{ast, codemap}; use syntax::ext::base; use syntax::ext::build::AstBuilder; use html::HtmlState; mod template; /// Trait meaning something can be turned into an ast::Item with configuration. pub trait Generate<Cfg> { /// Turn Self into an ast::Item with a configuration object. ...
/// /// /// impl Generate<()> for HtmlState { fn generate( self, sp: codemap::Span, cx: &mut base::ExtCtxt, _: () ) -> P<ast::Item> { let skin = self.skin.clone().unwrap(); let template_items = self.templates.into_iter().map( |template| template.gen...
random_line_split
mod.rs
use syntax::ptr::P; use syntax::{ast, codemap}; use syntax::ext::base; use syntax::ext::build::AstBuilder; use html::HtmlState; mod template; /// Trait meaning something can be turned into an ast::Item with configuration. pub trait Generate<Cfg> { /// Turn Self into an ast::Item with a configuration object. ...
( self, sp: codemap::Span, cx: &mut base::ExtCtxt, _: () ) -> P<ast::Item> { let skin = self.skin.clone().unwrap(); let template_items = self.templates.into_iter().map( |template| template.generate(sp, cx, ()) ).collect(); // we create ...
generate
identifier_name
mod.rs
use syntax::ptr::P; use syntax::{ast, codemap}; use syntax::ext::base; use syntax::ext::build::AstBuilder; use html::HtmlState; mod template; /// Trait meaning something can be turned into an ast::Item with configuration. pub trait Generate<Cfg> { /// Turn Self into an ast::Item with a configuration object. ...
}
{ let skin = self.skin.clone().unwrap(); let template_items = self.templates.into_iter().map( |template| template.generate(sp, cx, ()) ).collect(); // we create the module made of the created function cx.item_mod(sp, sp, skin, vec![], vec![], template_items) }
identifier_body
billow.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::billow::Billow; use image::GenericImage; use std::io::File; use time::precise_time_s; fn
() { let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0); println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); for x in range(0, img_size) { for y in range(0, im...
main
identifier_name
billow.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::billow::Billow; use image::GenericImage; use std::io::File; use time::precise_time_s; fn main()
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG); println!("billow.png saved"); println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0); }
{ let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0); println!("Noise seed is {}", ngen.get_seed()); let img_size = 512 as u32; let mut imbuf = image::ImageBuf::new(img_size, img_size); let start = precise_time_s(); for x in range(0, img_size) { for y in range(0, img_s...
identifier_body
billow.rs
// example.rs extern crate noise; extern crate image; extern crate time; use noise::gen::NoiseGen; use noise::gen::billow::Billow; use image::GenericImage; use std::io::File; use time::precise_time_s; fn main() { let mut ngen = Billow::new_rand(24, 0.5, 2.5, 100.0); println!("Noise seed is {}...
let n = ngen.get_value2d((x as f64), (y as f64)); let col = (n * 255.0) as u8; let pixel = image::Luma(col); imbuf.put_pixel(x, y, pixel); } } let end = precise_time_s(); let fout = File::create(&Path::new("billow.png")).unwrap(); let _ =...
let start = precise_time_s(); for x in range(0, img_size) { for y in range(0, img_size) {
random_line_split
live_timers.rs
use std::collections::HashMap; use platform::time::time_now; use super::StartTime; use super::Timing; #[derive(Debug, Clone, PartialEq)] pub struct LiveTimers { timers: HashMap<String, StartTime>, }
impl LiveTimers { pub fn new() -> LiveTimers { LiveTimers { timers: HashMap::new() } } pub fn get_timers(&self) -> &HashMap<String, StartTime> { &self.timers } pub fn start(&mut self, name: &str) -> StartTime { let start_time = time_now(); self.timers.insert(name....
random_line_split
live_timers.rs
use std::collections::HashMap; use platform::time::time_now; use super::StartTime; use super::Timing; #[derive(Debug, Clone, PartialEq)] pub struct LiveTimers { timers: HashMap<String, StartTime>, } impl LiveTimers { pub fn
() -> LiveTimers { LiveTimers { timers: HashMap::new() } } pub fn get_timers(&self) -> &HashMap<String, StartTime> { &self.timers } pub fn start(&mut self, name: &str) -> StartTime { let start_time = time_now(); self.timers.insert(name.to_string(), start_time.clone());...
new
identifier_name
live_timers.rs
use std::collections::HashMap; use platform::time::time_now; use super::StartTime; use super::Timing; #[derive(Debug, Clone, PartialEq)] pub struct LiveTimers { timers: HashMap<String, StartTime>, } impl LiveTimers { pub fn new() -> LiveTimers { LiveTimers { timers: HashMap::new() } } pub ...
let start_time = opt.unwrap(); let duration = stop_time - start_time; Timing::new(name, start_time, duration) } }
{ panic!("Tried to stop non-live timer: {:?}", name); }
conditional_block
live_timers.rs
use std::collections::HashMap; use platform::time::time_now; use super::StartTime; use super::Timing; #[derive(Debug, Clone, PartialEq)] pub struct LiveTimers { timers: HashMap<String, StartTime>, } impl LiveTimers { pub fn new() -> LiveTimers { LiveTimers { timers: HashMap::new() } } pub ...
pub fn start(&mut self, name: &str) -> StartTime { let start_time = time_now(); self.timers.insert(name.to_string(), start_time.clone()); start_time } pub fn stop(&mut self, name: &str) -> Timing { let stop_time = time_now(); let opt = self.timers.remove(name); ...
{ &self.timers }
identifier_body
try_chan.rs
// Copyright 2016 Google Inc. All rights reserved. // // 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...
{ test_mpsc() }
identifier_body
try_chan.rs
// Copyright 2016 Google Inc. All rights reserved. // // 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...
/* use xi_rpc::chan::Chan; pub fn test_chan() { let n_iter = 1000000; let chan1 = Chan::new(); let chan1s = chan1.clone(); let chan2 = Chan::new(); let chan2s = chan2.clone(); let thread1 = thread::spawn(move|| { for _ in 0..n_iter { chan2s.try_send(chan1.recv()); } ...
use std::thread; use std::sync::mpsc;
random_line_split
try_chan.rs
// Copyright 2016 Google Inc. All rights reserved. // // 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...
() { let n_iter = 1000000; let (chan1s, chan1) = mpsc::channel(); let (chan2s, chan2) = mpsc::channel(); let thread1 = thread::spawn(move|| { for _ in 0..n_iter { chan2s.send(chan1.recv()).unwrap(); } }); let thread2 = thread::spawn(move|| { for _ in 0..n_iter...
test_mpsc
identifier_name
get_type_id.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::any::Any; use core::any::TypeId; // #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub struct TypeId { // t: u64, // } // impl<T: Reflect +'static> Any f...
}
{ struct A; let x: A = A; let _: TypeId = x.get_type_id(); }
identifier_body
get_type_id.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::any::Any; use core::any::TypeId; // #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub struct TypeId { // t: u64, // } // impl<T: Reflect +'static> Any f...
} }
random_line_split
get_type_id.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::any::Any; use core::any::TypeId; // #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub struct TypeId { // t: u64, // } // impl<T: Reflect +'static> Any f...
; let x: A = A; let _: TypeId = x.get_type_id(); } }
A
identifier_name
sampler_renderer.rs
use core::{Camera, Integrator, Sampler, Scene}; use film::Spectrum; use linalg::ray_differential::RayDifferential; use integrator::{SurfaceIntegrator, VolumeIntegrator}; use renderer::Renderer; pub struct SamplerRenderer<'a, S: Sampler, C: Camera> { pub sampler: S, pub camera: C, pub surface_integrator:...
#[allow(unused_variables)] fn li(&self, scene: &Scene, ray: &RayDifferential, sample: &Sampler) -> Box<Spectrum> { unimplemented!() } #[allow(unused_variables)] fn transmittance(&self, scene: &Scene, ray: &RayDifferential, sam...
{ self.surface_integrator.preprocess(scene, &self.camera); self.volume_integrator.preprocess(scene, &self.camera); }
identifier_body
sampler_renderer.rs
use core::{Camera, Integrator, Sampler, Scene}; use film::Spectrum; use linalg::ray_differential::RayDifferential; use integrator::{SurfaceIntegrator, VolumeIntegrator}; use renderer::Renderer; pub struct SamplerRenderer<'a, S: Sampler, C: Camera> { pub sampler: S, pub camera: C, pub surface_integrator:...
fn new(sampler: S, camera: C, surface_integrator: &'a SurfaceIntegrator, volume_integrator: &'a VolumeIntegrator) -> SamplerRenderer<'a, S, C> { SamplerRenderer { sampler: sampler, camera: camera, surface_integrator: surface_int...
} impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> {
random_line_split
sampler_renderer.rs
use core::{Camera, Integrator, Sampler, Scene}; use film::Spectrum; use linalg::ray_differential::RayDifferential; use integrator::{SurfaceIntegrator, VolumeIntegrator}; use renderer::Renderer; pub struct
<'a, S: Sampler, C: Camera> { pub sampler: S, pub camera: C, pub surface_integrator: &'a SurfaceIntegrator, pub volume_integrator: &'a VolumeIntegrator, } impl<'a, S: Sampler, C: Camera> SamplerRenderer<'a, S, C> { fn new(sampler: S, camera: C, surface_integrator: &'a SurfaceI...
SamplerRenderer
identifier_name
rmeta.rs
// Copyright 2016 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 ...
// aux-build:rmeta_rlib.rs extern crate rmeta_aux; use rmeta_aux::Foo; pub fn main() { let _ = Foo { field: 42 }; }
// Test that using rlibs and rmeta dep crates work together. Specifically, that // there can be both an rmeta and an rlib file and rustc will prefer the rlib. // aux-build:rmeta_rmeta.rs
random_line_split
rmeta.rs
// Copyright 2016 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 _ = Foo { field: 42 }; }
identifier_body
rmeta.rs
// Copyright 2016 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 _ = Foo { field: 42 }; }
main
identifier_name
metadata.rs
use ape; use id3; use lewton::inside_ogg::OggStreamReader; use metaflac; use mp3_duration; use regex::Regex; use std::fs; use std::path::Path; use errors::*; use utils; use utils::AudioFormat; #[derive(Debug, Clone, PartialEq)] pub struct SongTags { pub disc_number: Option<u32>, pub track_number: Option<u32>, pub ...
let mp3_sample_tag = SongTags {duration: Some(0),..sample_tags.clone()}; assert_eq!(read(Path::new("test/sample.mp3")).unwrap(), mp3_sample_tag); assert_eq!(read(Path::new("test/sample.ogg")).unwrap(), sample_tags); assert_eq!(read(Path::new("test/sample.flac")).unwrap(), flac_sample_tag); }
year: Some(2016), }; let flac_sample_tag = SongTags {duration: Some(0), ..sample_tags.clone()};
random_line_split
metadata.rs
use ape; use id3; use lewton::inside_ogg::OggStreamReader; use metaflac; use mp3_duration; use regex::Regex; use std::fs; use std::path::Path; use errors::*; use utils; use utils::AudioFormat; #[derive(Debug, Clone, PartialEq)] pub struct SongTags { pub disc_number: Option<u32>, pub track_number: Option<u32>, pub ...
(path: &Path) -> Result<SongTags> { let tag = metaflac::Tag::read_from_path(path)?; let vorbis = tag.vorbis_comments().ok_or("Missing Vorbis comments")?; let disc_number = vorbis .get("DISCNUMBER") .and_then(|d| d[0].parse::<u32>().ok()); let year = vorbis.get("DATE").and_then(|d| d[0].parse::<i32>().ok()); le...
read_flac
identifier_name
metadata.rs
use ape; use id3; use lewton::inside_ogg::OggStreamReader; use metaflac; use mp3_duration; use regex::Regex; use std::fs; use std::path::Path; use errors::*; use utils; use utils::AudioFormat; #[derive(Debug, Clone, PartialEq)] pub struct SongTags { pub disc_number: Option<u32>, pub track_number: Option<u32>, pub ...
fn read_ape(path: &Path) -> Result<SongTags> { let tag = ape::read(path)?; let artist = tag.item("Artist").and_then(read_ape_string); let album = tag.item("Album").and_then(read_ape_string); let album_artist = tag.item("Album artist").and_then(read_ape_string); let title = tag.item("Title").and_then(read_ape_str...
{ match item.value { ape::ItemValue::Text(ref s) => { let format = Regex::new(r#"^\d+"#).unwrap(); if let Some(m) = format.find(s) { s[m.start()..m.end()].parse().ok() } else { None } } _ => None, } }
identifier_body
app.rs
use clap::{App, Arg}; const DEFAULT_RETRY_INTERVAL: &str = "1000"; const DEFAULT_UPDATE_INTERVAL: &str = "1000"; const DEFAULT_CALCULATION_THREADS: &str = "1"; const DEFAULT_CALCULATION_LIMIT: &str = "1000"; const DEFAULT_GENERATION_LIMIT: &str = "10"; const DEFAULT_MILESTONE_ADDRESS: &str = "KPWCHICGJZXKE9GSUDXZYUA...
.arg( Arg::with_name("retry_interval") .short("r") .long("retry-interval") .takes_value(true) .value_name("INTERVAL") .default_value(DEFAULT_RETRY_INTERVAL) .help("MySQL connect retry interval in milliseconds"), ) .arg( Arg::with_name("update_interval") ...
{ app_from_crate!() .arg( Arg::with_name("zmq_uri") .short("z") .long("zmq") .takes_value(true) .value_name("URI") .required(true) .help("ZMQ source server URI"), ) .arg( Arg::with_name("mysql_uri") .short("m") .long("mysql") ...
identifier_body
app.rs
use clap::{App, Arg}; const DEFAULT_RETRY_INTERVAL: &str = "1000"; const DEFAULT_UPDATE_INTERVAL: &str = "1000"; const DEFAULT_CALCULATION_THREADS: &str = "1"; const DEFAULT_CALCULATION_LIMIT: &str = "1000"; const DEFAULT_GENERATION_LIMIT: &str = "10"; const DEFAULT_MILESTONE_ADDRESS: &str = "KPWCHICGJZXKE9GSUDXZYUA...
<'a, 'b>() -> App<'a, 'b> { app_from_crate!() .arg( Arg::with_name("zmq_uri") .short("z") .long("zmq") .takes_value(true) .value_name("URI") .required(true) .help("ZMQ source server URI"), ) .arg( Arg::with_name("mysql_uri") .short("m") .lo...
build
identifier_name
app.rs
use clap::{App, Arg}; const DEFAULT_RETRY_INTERVAL: &str = "1000"; const DEFAULT_UPDATE_INTERVAL: &str = "1000"; const DEFAULT_CALCULATION_THREADS: &str = "1"; const DEFAULT_CALCULATION_LIMIT: &str = "1000"; const DEFAULT_GENERATION_LIMIT: &str = "10"; const DEFAULT_MILESTONE_ADDRESS: &str = "KPWCHICGJZXKE9GSUDXZYUA...
.help("ZMQ source server URI"), ) .arg( Arg::with_name("mysql_uri") .short("m") .long("mysql") .takes_value(true) .value_name("URI") .required(true) .help("MySQL destination server URI"), ) .arg( Arg::with_name("retry_interval") .short("r...
.value_name("URI") .required(true)
random_line_split
stdio.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn write(&self, data: &[u8]) -> io::Result<usize> { let fd = FileDesc::new(libc::STDOUT_FILENO); let ret = fd.write(data); fd.into_raw(); return ret; } } impl Stderr { pub fn new() -> io::Result<Stderr> { Ok(Stderr(())) } pub fn write(&self, data: &[u8]) -> io::Re...
{ Ok(Stdout(())) }
identifier_body
stdio.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(()); impl Stdin { pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) } pub fn read(&self, data: &mut [u8]) -> io::Result<usize> { let fd = FileDesc::new(libc::STDIN_FILENO); let ret = fd.read(data); fd.into_raw(); return ret; } } impl Stdout { pub fn new() -> io::Resul...
Stderr
identifier_name
stdio.rs
// Copyright 2015 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. #[cfg(stage0)] use prelude::v1::*; use io; use libc; use sys::fd::FileDesc; pub struct Stdin(()); pub struct Stdout(()); pub struct Stderr(()); impl Stdin { pub fn new() -> io::Result<Stdin> { Ok(Stdin(())) } pub fn read(&self, data: &mut [u8]) -> io::Result<usize> { ...
// // 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
cttz32.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::cttz32; // pub fn cttz32(x: u32) -> u32; macro_rules! cttz32_test { ($value:expr, $BITS:expr) => ({ let x: u32 = $value; let result: u32 = unsafe { cttz32(x) }; assert_eq!(result, $BITS);...
cttz32_test!(0x00080000, 19); cttz32_test!(0x00100000, 20); cttz32_test!(0x00200000, 21); cttz32_test!(0x00400000, 22); cttz32_test!(0x00800000, 23); cttz32_test!(0x01000000, 24); cttz32_test!(0x02000000, 25); cttz32_test!(0x04000000, 26); cttz32_test!(0x08000000, 27); cttz32_test!(0x10000000, 28); cttz32_te...
{ cttz32_test!(0x00000001, 0); cttz32_test!(0x00000002, 1); cttz32_test!(0x00000004, 2); cttz32_test!(0x00000008, 3); cttz32_test!(0x00000010, 4); cttz32_test!(0x00000020, 5); cttz32_test!(0x00000040, 6); cttz32_test!(0x00000080, 7); cttz32_test!(0x00000100, 8); cttz32_test!(0x00000200, 9); cttz32_test!(0x00...
identifier_body
cttz32.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::cttz32; // pub fn cttz32(x: u32) -> u32; macro_rules! cttz32_test { ($value:expr, $BITS:expr) => ({ let x: u32 = $value; let result: u32 = unsafe { cttz32(x) }; assert_eq!(result, $BITS);...
() { cttz32_test!(0x00000001, 0); cttz32_test!(0x00000002, 1); cttz32_test!(0x00000004, 2); cttz32_test!(0x00000008, 3); cttz32_test!(0x00000010, 4); cttz32_test!(0x00000020, 5); cttz32_test!(0x00000040, 6); cttz32_test!(0x00000080, 7); cttz32_test!(0x00000100, 8); cttz32_test!(0x00000200, 9); cttz32_test!(0...
cttz32_test1
identifier_name
cttz32.rs
#![feature(core, core_intrinsics)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::cttz32; // pub fn cttz32(x: u32) -> u32; macro_rules! cttz32_test { ($value:expr, $BITS:expr) => ({ let x: u32 = $value; let result: u32 = unsafe { cttz32(x) }; assert_eq!(result, $BITS);...
cttz32_test!(0x00000080, 7); cttz32_test!(0x00000100, 8); cttz32_test!(0x00000200, 9); cttz32_test!(0x00000400, 10); cttz32_test!(0x00000800, 11); cttz32_test!(0x00001000, 12); cttz32_test!(0x00002000, 13); cttz32_test!(0x00004000, 14); cttz32_test!(0x00008000, 15); cttz32_test!(0x00010000, 16); cttz32_test!...
cttz32_test!(0x00000010, 4); cttz32_test!(0x00000020, 5); cttz32_test!(0x00000040, 6);
random_line_split
raw.rs
extern crate libsqlite3_sys as ffi; extern crate libc; use std::ffi::{CString, CStr}; use std::io::{stderr, Write}; use std::{ptr, str}; use result::*; use result::Error::DatabaseError; #[allow(missing_debug_implementations, missing_copy_implementations)] pub struct RawConnection { pub internal_connection: *mut ...
(err_msg: *const libc::c_char) -> String { let msg = unsafe { let bytes = CStr::from_ptr(err_msg).to_bytes(); str::from_utf8_unchecked(bytes).into() }; unsafe { ffi::sqlite3_free(err_msg as *mut libc::c_void) }; msg }
convert_to_string_and_free
identifier_name
raw.rs
extern crate libsqlite3_sys as ffi; extern crate libc; use std::ffi::{CString, CStr}; use std::io::{stderr, Write}; use std::{ptr, str}; use result::*; use result::Error::DatabaseError; #[allow(missing_debug_implementations, missing_copy_implementations)] pub struct RawConnection { pub internal_connection: *mut ...
else { Ok(()) } } pub fn rows_affected_by_last_query(&self) -> usize { unsafe { ffi::sqlite3_changes(self.internal_connection) as usize } } pub fn last_error_message(&self) -> String { let c_str = unsafe { CStr::from_ptr(ffi::sqlite3_errmsg(self.internal_connection...
{ let msg = convert_to_string_and_free(err_msg); let error_kind = DatabaseErrorKind::__Unknown; Err(DatabaseError(error_kind, Box::new(msg))) }
conditional_block