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
root.rs
/* The library provides a simple datastructure to access geolocated labels with an additional elimination time t and a label size factor. The library provides method to query a set of such labels with a bounding box and a minimum elimination time. Copyright (C) {2017} {Filip Krumpe <filip.krumpe@fmi.u...
/// /// Compare two Root refs with respect to the y value. /// fn order_by_y(first: &Self, second: &Self) -> Ordering { if first.m_y < second.m_y { Ordering::Less } else if first.m_y > second.m_y { Ordering::Greater } else { Ordering::Equal ...
{ if first.m_x < second.m_x { Ordering::Less } else if first.m_x > second.m_x { Ordering::Greater } else { Ordering::Equal } }
identifier_body
uninhabited_enum_branching.rs
//! A pass that eliminates branches on uninhabited enum variants. use crate::MirPass; use rustc_data_structures::stable_set::FxHashSet; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets, TerminatorKind, }; use rustc_middle::ty::layout::TyAndLayout; ...
} fn variant_discriminants<'tcx>( layout: &TyAndLayout<'tcx>, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>, ) -> FxHashSet<u128> { match &layout.variants { Variants::Single { index } => { let mut res = FxHashSet::default(); res.insert(index.as_u32() as u128); res ...
{ let terminator = block_data.terminator(); // Only bother checking blocks which terminate by switching on a local. if let Some(local) = get_discriminant_local(&terminator.kind) { let stmt_before_term = (!block_data.statements.is_empty()) .then(|| &block_data.statements[block_data.state...
identifier_body
uninhabited_enum_branching.rs
//! A pass that eliminates branches on uninhabited enum variants. use crate::MirPass; use rustc_data_structures::stable_set::FxHashSet; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets, TerminatorKind, }; use rustc_middle::ty::layout::TyAndLayout; ...
/// If the basic block terminates by switching on a discriminant, this returns the `Ty` the /// discriminant is read from. Otherwise, returns None. fn get_switched_on_type<'tcx>( block_data: &BasicBlockData<'tcx>, tcx: TyCtxt<'tcx>, body: &Body<'tcx>, ) -> Option<Ty<'tcx>> { let terminator = block_data....
None } }
random_line_split
uninhabited_enum_branching.rs
//! A pass that eliminates branches on uninhabited enum variants. use crate::MirPass; use rustc_data_structures::stable_set::FxHashSet; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets, TerminatorKind, }; use rustc_middle::ty::layout::TyAndLayout; ...
Variants::Multiple { variants,.. } => variants .iter_enumerated() .filter_map(|(idx, layout)| { (layout.abi!= Abi::Uninhabited) .then(|| ty.discriminant_for_variant(tcx, idx).unwrap().val) }) .collect(), } } impl<'tcx> MirPass...
{ let mut res = FxHashSet::default(); res.insert(index.as_u32() as u128); res }
conditional_block
uninhabited_enum_branching.rs
//! A pass that eliminates branches on uninhabited enum variants. use crate::MirPass; use rustc_data_structures::stable_set::FxHashSet; use rustc_middle::mir::{ BasicBlock, BasicBlockData, Body, Local, Operand, Rvalue, StatementKind, SwitchTargets, TerminatorKind, }; use rustc_middle::ty::layout::TyAndLayout; ...
<'tcx>( layout: &TyAndLayout<'tcx>, ty: Ty<'tcx>, tcx: TyCtxt<'tcx>, ) -> FxHashSet<u128> { match &layout.variants { Variants::Single { index } => { let mut res = FxHashSet::default(); res.insert(index.as_u32() as u128); res } Variants::Multipl...
variant_discriminants
identifier_name
practicalengine.rs
#![allow(unstable)] extern crate time; extern crate water; use water::Net; use water::Endpoint; use water::Message; use water::ID; use water::Duration; use time::Timespec; use std::thread::JoinGuard; use std::thread::Thread; use std::vec::Vec; use std::collections::HashMap; use std::sync::Arc; use s...
(mep: Endpoint, corecnt: usize) { let mut endpoints: Vec<Endpoint> = Vec::new(); let mut workerthreads: Vec<JoinGuard<()>> = Vec::new(); let mut pending: HashMap<u64, WorkPending> = HashMap::new(); // Create net for this pipeline. let net = Net::new(400); let ep = net.new_endpoint_withid...
thread_pipelinemanager
identifier_name
practicalengine.rs
#![allow(unstable)] extern crate time; extern crate water; use water::Net; use water::Endpoint; use water::Message; use water::ID; use water::Duration; use time::Timespec; use std::thread::JoinGuard; use std::thread::Thread; use std::vec::Vec; use std::collections::HashMap; use std::sync::Arc; use s...
epid: msg_srceid, id: request.id, need: corecnt, work: Vec::new(), totalsize: datalen, }); for chkndx in range(0us, (corecnt - 1) as usize) { let work = Work { ...
epsid: msg_srcsid,
random_line_split
practicalengine.rs
#![allow(unstable)] extern crate time; extern crate water; use water::Net; use water::Endpoint; use water::Message; use water::ID; use water::Duration; use time::Timespec; use std::thread::JoinGuard; use std::thread::Thread; use std::vec::Vec; use std::collections::HashMap; use std::sync::Arc; use s...
let msg = result.unwrap(); if msg.is_type::<Terminate>() { return; } // Figure out the type of message. if msg.is_type::<Work>() { let work: Work = msg.get_sync().get_payload(); println!("[worker] working on id {:x} and tail {:x}...
{ return; }
conditional_block
service.rs
use futures::{Future, IntoFuture}; use std::io; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; /// An asynchronous function from `Request` to a `Response`. /// /// The `Service` trait is a simplified interface making it easy to write /// network applications in a modular and reusable way, decoupled from th...
(&self) -> SimpleService<F, R> { SimpleService { f: self.f.clone(), _ty: PhantomData, } } } impl<T> NewService for T where T: Service + Clone, { type Item = T; type Req = T::Req; type Resp = T::Resp; type Error = T::Error; fn new_service(&self) -> io...
clone
identifier_name
service.rs
use futures::{Future, IntoFuture}; use std::io; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; /// An asynchronous function from `Request` to a `Response`. /// /// The `Service` trait is a simplified interface making it easy to write /// network applications in a modular and reusable way, decoupled from th...
/// impl<T> Service for Timeout<T> /// where T: Service, /// T::Error: From<Expired>, /// { /// type Req = T::Req; /// type Resp = T::Resp; /// type Error = T::Error; /// type Fut = Box<Future<Item = Self::Resp, Error = Self::Error>>; /// /// fn call(&self, req: Self::Req) -> Self::Fut...
/// } ///
random_line_split
service.rs
use futures::{Future, IntoFuture}; use std::io; use std::marker::PhantomData; use std::sync::{Arc, Mutex}; /// An asynchronous function from `Request` to a `Response`. /// /// The `Service` trait is a simplified interface making it easy to write /// network applications in a modular and reusable way, decoupled from th...
} impl<T> NewService for T where T: Service + Clone, { type Item = T; type Req = T::Req; type Resp = T::Resp; type Error = T::Error; fn new_service(&self) -> io::Result<T> { Ok(self.clone()) } }
{ SimpleService { f: self.f.clone(), _ty: PhantomData, } }
identifier_body
char.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 ...
assert_eq!(c, d); assert_eq!(d, c); assert_eq!(d, 'x'); assert_eq!('x', d); }
random_line_split
char.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 c: char = 'x'; let d: char = 'x'; assert_eq!(c, 'x'); assert_eq!('x', c); assert_eq!(c, c); assert_eq!(c, d); assert_eq!(d, c); assert_eq!(d, 'x'); assert_eq!('x', d); }
identifier_body
char.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 c: char = 'x'; let d: char = 'x'; assert_eq!(c, 'x'); assert_eq!('x', c); assert_eq!(c, c); assert_eq!(c, d); assert_eq!(d, c); assert_eq!(d, 'x'); assert_eq!('x', d); }
main
identifier_name
binary_tree.rs
pub struct Node<T: Clone> { elem: T, left: Box<Tree<T>>, right: Box<Tree<T>>, } /* impl<T: Clone> Drop for Node<T> { fn drop(self) { println!("> Dropping {}", self.name); } } */ impl<T: Clone> Node<T> { /// Allocates a new binary tree node to contain the given element. pub fn new(e...
pub fn is_nil(&self) -> bool { match *self { Tree::Nil => true, _ => false } } /// Returns a clone of the element stored in the root node. /// /// Panics if there is no root node. pub fn peek(&self) -> T { match *self { Tree:...
{ Tree::Nil }
identifier_body
binary_tree.rs
pub struct Node<T: Clone> { elem: T, left: Box<Tree<T>>, right: Box<Tree<T>>, } /* impl<T: Clone> Drop for Node<T> { fn drop(self) { println!("> Dropping {}", self.name); } } */ impl<T: Clone> Node<T> { /// Allocates a new binary tree node to contain the given element. pub fn new(e...
(&self) -> T { match *self { Tree::Nil => panic!(), Tree::Node(ref n) => (*n).elem.clone() } } /* /// The given element is cloned, and this clone is stored at the root of /// the tree. /// /// If the tree is `Nil`, then a node is made in-place to hold the...
peek
identifier_name
binary_tree.rs
pub struct Node<T: Clone> {
} /* impl<T: Clone> Drop for Node<T> { fn drop(self) { println!("> Dropping {}", self.name); } } */ impl<T: Clone> Node<T> { /// Allocates a new binary tree node to contain the given element. pub fn new(elem: T) -> Node<T> { Node { elem: elem, left: box Tree::Ni...
elem: T, left: Box<Tree<T>>, right: Box<Tree<T>>,
random_line_split
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn nodes(&self) -> dot::Nodes<Node> { let mut set = FnvHashSet(); for node in self.node_ids.keys() { set.insert(*node); } debug!("constraint graph has {} nodes", set.len()); se...
{ (Node::Region(ty::ReScope(sub)), Node::Region(ty::ReScope(sup))) }
conditional_block
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, n: &Node) -> dot::LabelText { match *n { Node::RegionVid(n_vid) => dot::LabelText::label(format!("{:?}", n_vid)), Node::Region(n_rgn) => dot::LabelText::label(format!("{}", n_rgn.repr(self.tcx))), } } fn edge_label(&self, e: &Edge) ...
node_label
identifier_name
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn target(&self, edge: &Edge) -> Node { let (_, n2) = edge_to_nodes(edge); debug!("edge {:?} has target {:?}", edge, n2); n2 } } pub type ConstraintMap<'tcx> = FnvHashMap<Constraint, SubregionOrigin<'tcx>>; fn dump_region_constraints_to<'a, 'tcx:'a >(tcx: &'a ty::ctxt<'tcx>, ...
debug!("edge {:?} has source {:?}", edge, n1); n1 }
random_line_split
graphviz.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn edge_label(&self, e: &Edge) -> dot::LabelText { match *e { Edge::Constraint(ref c) => dot::LabelText::label(format!("{}", self.map.get(c).unwrap().repr(self.tcx))), Edge::EnclScope(..) => dot::LabelText::label(format!("(enclosed)")), } ...
{ match *n { Node::RegionVid(n_vid) => dot::LabelText::label(format!("{:?}", n_vid)), Node::Region(n_rgn) => dot::LabelText::label(format!("{}", n_rgn.repr(self.tcx))), } }
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/. */ #![feature(ascii)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_syntax)] #![feature(const_...
assert_eq!(js::jsapi::JS_Init(), true); SetDOMProxyInformation(ptr::null(), 0, Some(script_thread::shadow_check_callback)); } // Create the global vtables used by the (generated) DOM // bindings to implement JS proxies. RegisterBindings::RegisterProxyHandlers(); perform_platform_sp...
#[allow(unsafe_code)] pub fn init() { unsafe {
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #![feature(ascii)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_syntax)] #![feature(const_...
{ unsafe { assert_eq!(js::jsapi::JS_Init(), true); SetDOMProxyInformation(ptr::null(), 0, Some(script_thread::shadow_check_callback)); } // Create the global vtables used by the (generated) DOM // bindings to implement JS proxies. RegisterBindings::RegisterProxyHandlers(); perf...
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/. */ #![feature(ascii)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_syntax)] #![feature(const_...
() { use std::mem; // 4096 is default max on many linux systems const MAX_FILE_LIMIT: libc::rlim_t = 4096; // Bump up our number of file descriptors to save us from impending doom caused by an onslaught // of iframes. unsafe { let mut rlim: libc::rlimit = mem::uninitialized(); m...
perform_platform_specific_initialization
identifier_name
cg_clif.rs
#![feature(rustc_private, once_cell)] extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_interface; extern crate rustc_session; extern crate rustc_target; use std::lazy::SyncLazy; use std::panic; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; us...
}
} std::process::exit(exit_code)
random_line_split
cg_clif.rs
#![feature(rustc_private, once_cell)] extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_interface; extern crate rustc_session; extern crate rustc_target; use std::lazy::SyncLazy; use std::panic; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; us...
{ time_passes: bool, } impl rustc_driver::Callbacks for CraneliftPassesCallbacks { fn config(&mut self, config: &mut interface::Config) { // If a --prints=... option has been given, we don't print the "total" // time because it will mess up the --prints output. See #64339. self.time_pa...
CraneliftPassesCallbacks
identifier_name
cg_clif.rs
#![feature(rustc_private, once_cell)] extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_interface; extern crate rustc_session; extern crate rustc_target; use std::lazy::SyncLazy; use std::panic; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; us...
Box::new(rustc_codegen_cranelift::CraneliftCodegenBackend { config: None }) }))); run_compiler.run() }); if callbacks.time_passes { let end_rss = get_resident_set_size(); print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss); } std::proc...
{ let start_time = std::time::Instant::now(); let start_rss = get_resident_set_size(); rustc_driver::init_rustc_env_logger(); let mut callbacks = CraneliftPassesCallbacks::default(); SyncLazy::force(&DEFAULT_HOOK); // Install ice hook let exit_code = rustc_driver::catch_with_exit_code(|| { ...
identifier_body
cg_clif.rs
#![feature(rustc_private, once_cell)] extern crate rustc_data_structures; extern crate rustc_driver; extern crate rustc_interface; extern crate rustc_session; extern crate rustc_target; use std::lazy::SyncLazy; use std::panic; use rustc_data_structures::profiling::{get_resident_set_size, print_time_passes_entry}; us...
std::process::exit(exit_code) }
{ let end_rss = get_resident_set_size(); print_time_passes_entry("total", start_time.elapsed(), start_rss, end_rss); }
conditional_block
sysex.rs
// This file is part of a6-tools. // Copyright (C) 2017 Jeffrey Sharp // // a6-tools 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 later version....
for v in src { // Add 8 input bits. data |= (*v as u16) << bits; // Yield 7 bits. Accrue 1 leftover bit for next iteration. dst.push((data & 0x7F) as u8); data >>= 7; bits += 1; // Every 7 iterations, 7 leftover bits have accrued. // Consume them t...
random_line_split
sysex.rs
// This file is part of a6-tools. // Copyright (C) 2017 Jeffrey Sharp // // a6-tools 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 later version....
else { fire!(on_msg, start, &buf[..len]) } start = next; break // to state A }, Some(_) => { let end = next - 1; fire!(on_err, start, end - start, UnexpectedByte);...
{ fire!(on_err, start, next - start, Overflow) }
conditional_block
sysex.rs
// This file is part of a6-tools. // Copyright (C) 2017 Jeffrey Sharp // // a6-tools 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 later version....
() { let events = run_read(b"any", 10); assert_eq!(events.len(), 1); assert_eq!(events[0], Error { pos: 0, len: 3, err: NotSysEx }); } #[test] fn test_read_sysex_sysex() { let events = run_read(b"\xF0msg\xF7", 10); assert_eq!(events.len(), 1); assert_eq!(even...
test_read_sysex_junk
identifier_name
lib.rs
extern crate ntlm; extern crate rustc_serialize as serialize; use ntlm::messages::{MessageType1, BinaryEncodable}; use serialize::base64::{ToBase64, STANDARD}; #[test] fn new_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_byt...
#[test] fn decode_message_type_1() { }
{ let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); let enc = m.encode(); assert_eq!(enc.to_base64(STANDARD), "TlRMTVNTUAABAAAAAAAAAAAEAAQAKQAAAAkACQAgAABsb2NhbGhvc3R0ZXN0"); }
identifier_body
lib.rs
extern crate ntlm; extern crate rustc_serialize as serialize; use ntlm::messages::{MessageType1, BinaryEncodable}; use serialize::base64::{ToBase64, STANDARD}; #[test] fn
() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); if String::from_utf8(m.host).unwrap() == host && String::from_utf8(m.domain).unwrap() == domain { assert!(true); } else { assert!(false); } } #[...
new_message_type_1
identifier_name
lib.rs
extern crate ntlm; extern crate rustc_serialize as serialize; use ntlm::messages::{MessageType1, BinaryEncodable}; use serialize::base64::{ToBase64, STANDARD}; #[test] fn new_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_byt...
else { assert!(false); } } #[test] fn encode_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); let enc = m.encode(); assert_eq!(enc.to_base64(STANDARD), "TlRMTVNTUAABAAAAAAAAAAAEAAQ...
{ assert!(true); }
conditional_block
lib.rs
extern crate ntlm; extern crate rustc_serialize as serialize; use ntlm::messages::{MessageType1, BinaryEncodable}; use serialize::base64::{ToBase64, STANDARD}; #[test] fn new_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_byt...
} } #[test] fn encode_message_type_1() { let host = String::from("localhost"); let domain = String::from("test"); let m = MessageType1::new(&host.clone().into_bytes(), &domain.clone().into_bytes()); let enc = m.encode(); assert_eq!(enc.to_base64(STANDARD), "TlRMTVNTUAABAAAAAAAAAAAEAAQAKQAAAAkACQAgAABsb2NhbGhvc...
if String::from_utf8(m.host).unwrap() == host && String::from_utf8(m.domain).unwrap() == domain { assert!(true); } else { assert!(false);
random_line_split
utils.rs
use libusb::{ LogLevel, Context, DeviceHandle, AsyncGroup, Result as UsbResult, Error, }; use consts; pub struct UsbWrapper { context: &'static Context, pub handle: &'static DeviceHandle<'static>, has_kernel_driver0: bool, has_kernel_driver1: bool, pub async_group: &'static...
} } Err(Error::NoDevice) } fn detach(handle: &mut DeviceHandle, iface: u8) -> UsbResult<bool> { match handle.kernel_driver_active(iface) { Ok(true) => { try!(handle.detach_kernel_driver(iface)); Ok(true) }, _ => Ok(false) } }
{ let devices = try!(context.devices()); for d in devices.iter() { let dd = match d.device_descriptor() { Ok(dd) => dd, Err(_) => continue }; if dd.vendor_id() == consts::VENDOR_ID && dd.product_id() == consts::PRODUCT_ID { let mut handle = try!(d.open...
identifier_body
utils.rs
use libusb::{ LogLevel, Context, DeviceHandle, AsyncGroup, Result as UsbResult, Error, }; use consts; pub struct UsbWrapper { context: &'static Context, pub handle: &'static DeviceHandle<'static>, has_kernel_driver0: bool, has_kernel_driver1: bool, pub async_group: &'static...
let has_kernel_driver1 = try!(detach(&mut handle, 1)); // claim interfaces try!(handle.claim_interface(0)); try!(handle.claim_interface(1)); // reset keyboard to get clean status try!(handle.reset()); return Ok((handle, has_kernel_drive...
random_line_split
utils.rs
use libusb::{ LogLevel, Context, DeviceHandle, AsyncGroup, Result as UsbResult, Error, }; use consts; pub struct UsbWrapper { context: &'static Context, pub handle: &'static DeviceHandle<'static>, has_kernel_driver0: bool, has_kernel_driver1: bool, pub async_group: &'static...
, _ => Ok(false) } }
{ try!(handle.detach_kernel_driver(iface)); Ok(true) }
conditional_block
utils.rs
use libusb::{ LogLevel, Context, DeviceHandle, AsyncGroup, Result as UsbResult, Error, }; use consts; pub struct
{ context: &'static Context, pub handle: &'static DeviceHandle<'static>, has_kernel_driver0: bool, has_kernel_driver1: bool, pub async_group: &'static mut AsyncGroup<'static>, } impl UsbWrapper { pub fn new() -> UsbResult<UsbWrapper> { // We must leak both context and handle and async_...
UsbWrapper
identifier_name
display_list_builder.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/. */ //! Constructs display lists from boxes. use layout::context::LayoutContext; use geom::{Point2D, Rect, Size2D}; ...
<'a> { ctx: &'a LayoutContext, /// A list of render layers that we've built up, root layer not included. layers: SmallVec0<RenderLayer>, /// The dirty rect. dirty: Rect<Au>, } /// Information needed at each step of the display list building traversal. pub struct DisplayListBuildingInfo { /// ...
DisplayListBuilder
identifier_name
display_list_builder.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/. */ //! Constructs display lists from boxes. use layout::context::LayoutContext; use geom::{Point2D, Rect, Size2D}; ...
}
{ gfx::color::rgba(self.red, self.green, self.blue, self.alpha) }
identifier_body
display_list_builder.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/. */ //! Constructs display lists from boxes. use layout::context::LayoutContext; use geom::{Point2D, Rect, Size2D}; ...
impl ToGfxColor for style::computed_values::RGBA { fn to_gfx_color(&self) -> gfx::color::Color { gfx::color::rgba(self.red, self.green, self.blue, self.alpha) } }
}
random_line_split
builtin.rs
// Copyright 2015, 2016 Ethcore (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 later version....
// along with Parity. If not, see <http://www.gnu.org/licenses/>. use page::handler; use std::sync::Arc; use endpoint::{Endpoint, EndpointInfo, EndpointPath, Handler}; use parity_dapps::{WebApp, File, Info}; pub struct PageEndpoint<T : WebApp +'static> { /// Content of the files pub app: Arc<T>, /// Prefix to str...
random_line_split
builtin.rs
// Copyright 2015, 2016 Ethcore (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 later version....
(&self) -> &str { self.file().content_type } fn is_drained(&self) -> bool { self.write_pos == self.file().content.len() } fn next_chunk(&mut self) -> &[u8] { &self.file().content[self.write_pos..] } fn bytes_written(&mut self, bytes: usize) { self.write_pos += bytes; } }
content_type
identifier_name
symbols.rs
use std::str::FromStr; #[derive(Copy, Debug, PartialEq, Clone)] pub enum Symbols { ParenOpen, ParenClose, SBracketOpen, SBracketClose, CBracketOpen, CBracketClose, Period, Comma, Colon, Caret, GreaterThan, LessThan, GreaterThanEqual, LessThanEqual, Plus, ...
(s: &str) -> Result<Symbols, String> { match s { "(" => Ok(Symbols::ParenOpen), ")" => Ok(Symbols::ParenClose), "[" => Ok(Symbols::SBracketOpen), "]" => Ok(Symbols::SBracketClose), "{" => Ok(Symbols::CBracketOpen), "}" => Ok(Symbols::...
from_str
identifier_name
symbols.rs
use std::str::FromStr; #[derive(Copy, Debug, PartialEq, Clone)] pub enum Symbols { ParenOpen, ParenClose, SBracketOpen, SBracketClose, CBracketOpen, CBracketClose, Period, Comma, Colon, Caret, GreaterThan, LessThan, GreaterThanEqual, LessThanEqual, Plus, ...
impl FromStr for Symbols { type Err = String; fn from_str(s: &str) -> Result<Symbols, String> { match s { "(" => Ok(Symbols::ParenOpen), ")" => Ok(Symbols::ParenClose), "[" => Ok(Symbols::SBracketOpen), "]" => Ok(Symbols::SBracketClose), "...
PercentEquals, RightThinArrow, }
random_line_split
parser.rs
use crate::branch::Branch; use crate::dictionary::Dictionary; use crate::state::InterpState; use crate::word::Word; use std::rc::Rc; /// Takes a chars iterator and returns all characters up to the next whitespace, /// excluding the whitespace character. Returns `None` the `chars` iterator is /// exhausted. pub fn next...
{ let mut branches: Vec<Branch> = Vec::new(); while let Some(word_str) = next_word(code) { if let Some(branch) = parse_word(&word_str, code, dict, state) { branches.push(branch); } } branches }
identifier_body
parser.rs
use crate::branch::Branch; use crate::dictionary::Dictionary; use crate::state::InterpState; use crate::word::Word; use std::rc::Rc; /// Takes a chars iterator and returns all characters up to the next whitespace, /// excluding the whitespace character. Returns `None` the `chars` iterator is /// exhausted. pub fn next...
<T: Iterator<Item = char>>( code: &mut T, dict: &mut Dictionary, state: &mut InterpState, ) -> Vec<Branch> { let mut branches: Vec<Branch> = Vec::new(); while let Some(word_str) = next_word(code) { if let Some(branch) = parse_word(&word_str, code, dict, state) { branches.push(bra...
parse
identifier_name
parser.rs
use crate::branch::Branch; use crate::dictionary::Dictionary; use crate::state::InterpState; use crate::word::Word; use std::rc::Rc; /// Takes a chars iterator and returns all characters up to the next whitespace, /// excluding the whitespace character. Returns `None` the `chars` iterator is /// exhausted. pub fn next...
_ => {} } if let Some(branch) = parse_word(&inner_word_str, chars, dict, state) { if inelse { elsebranches.push(branch); } else { ifbranches.push(branch...
while let Some(inner_word_str) = next_word(chars) { match dict.get(&inner_word_str) { Some(Word::Else) => inelse = true, Some(Word::Then) => break,
random_line_split
hostname.rs
#![crate_name = "uu_hostname"] /* * This file is part of the uutils coreutils package. * * (c) Alan Andrade <alan.andradec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[cfg(...
output.push_str(&ip); output.push_str(" "); hashset.insert(addr); } } let len = output.len(); if len > 0 { println!("{}", &output[0..len - 1]); ...
{ let len = ip.len(); ip.truncate(len - 2); }
conditional_block
hostname.rs
#![crate_name = "uu_hostname"] /* * This file is part of the uutils coreutils package. * * (c) Alan Andrade <alan.andradec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[cfg(...
{ use std::ffi::OsStr; let wide_name = OsStr::new(name).to_wide_null(); let err = unsafe { SetComputerNameExW(ComputerNamePhysicalDnsHostname, wide_name.as_ptr()) }; if err == 0 { // NOTE: the above is correct, failure is when the function returns 0 apparently Err(io::Error::last_os_e...
identifier_body
hostname.rs
#![crate_name = "uu_hostname"]
/* * This file is part of the uutils coreutils package. * * (c) Alan Andrade <alan.andradec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[cfg(windows)] extern crate winapi; ...
random_line_split
hostname.rs
#![crate_name = "uu_hostname"] /* * This file is part of the uutils coreutils package. * * (c) Alan Andrade <alan.andradec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; #[cfg(...
() -> io::Result<String> { use std::ffi::CStr; let namelen = 256; let mut name: Vec<u8> = repeat(0).take(namelen).collect(); let err = unsafe { gethostname( name.as_mut_ptr() as *mut libc::c_char, namelen as libc::size_t, ) }; if err == 0 { let n...
xgethostname
identifier_name
font.rs
use {JamResult, JamError}; use rusttype::{self, FontCollection}; use {FontLoadError, load_file_contents}; use std::path::Path; use render::read_directory_paths; pub struct OurFont { pub font: rusttype::Font<'static>, } pub fn load_font(full_path: &Path) -> Result<OurFont, FontLoadError> { let bytes = load_fil...
} } Ok(fonts) }
if let Some(extension) = path.extension().and_then(|p| p.to_str()).map(|s| s.to_lowercase()) { if extension == "ttf" { let font = load_font(path.as_path()).map_err(JamError::FontLoadError)?; fonts.push(font); }
random_line_split
font.rs
use {JamResult, JamError}; use rusttype::{self, FontCollection}; use {FontLoadError, load_file_contents}; use std::path::Path; use render::read_directory_paths; pub struct OurFont { pub font: rusttype::Font<'static>, } pub fn load_font(full_path: &Path) -> Result<OurFont, FontLoadError> { let bytes = load_f...
(full_path: &Path) -> JamResult<Vec<OurFont>> { let mut fonts = Vec::new(); let mut paths = read_directory_paths(full_path)?; paths.sort(); println!("sorted paths for fonts -> {:?}", paths); for path in paths { if let Some(extension) = path.extension().and_then(|p| p.to_str()).map(|s| s....
load_fonts_in_path
identifier_name
font.rs
use {JamResult, JamError}; use rusttype::{self, FontCollection}; use {FontLoadError, load_file_contents}; use std::path::Path; use render::read_directory_paths; pub struct OurFont { pub font: rusttype::Font<'static>, } pub fn load_font(full_path: &Path) -> Result<OurFont, FontLoadError> { let bytes = load_f...
} } Ok(fonts) }
{ let font = load_font(path.as_path()).map_err(JamError::FontLoadError)?; fonts.push(font); }
conditional_block
font.rs
use {JamResult, JamError}; use rusttype::{self, FontCollection}; use {FontLoadError, load_file_contents}; use std::path::Path; use render::read_directory_paths; pub struct OurFont { pub font: rusttype::Font<'static>, } pub fn load_font(full_path: &Path) -> Result<OurFont, FontLoadError> { let bytes = load_f...
{ let mut fonts = Vec::new(); let mut paths = read_directory_paths(full_path)?; paths.sort(); println!("sorted paths for fonts -> {:?}", paths); for path in paths { if let Some(extension) = path.extension().and_then(|p| p.to_str()).map(|s| s.to_lowercase()) { if extension == ...
identifier_body
mod.rs
mod builder; mod master_key; mod tlv; use bytes; use decompress; use {Error, FileType}; use self::builder::HeaderBuilder; use protected::ProtectedStream; use std::io::Read; #[derive(Debug, PartialEq)] enum CipherType { Aes, } #[derive(Debug, PartialEq)] enum CompressionType { None, Gzip, } #[derive(De...
{ None, Rc4, Salsa20, } #[derive(Debug)] pub struct Header { version: u32, cipher: CipherType, compression: CompressionType, master_seed: [u8; 32], transform_seed: [u8; 32], transform_rounds: u64, encryption_iv: [u8; 16], protected_stream_key: [u8; 32], stream_start_byt...
InnerRandomStreamType
identifier_name
mod.rs
mod builder; mod master_key; mod tlv; use bytes; use decompress; use {Error, FileType}; use self::builder::HeaderBuilder; use protected::ProtectedStream; use std::io::Read; #[derive(Debug, PartialEq)] enum CipherType { Aes, } #[derive(Debug, PartialEq)] enum CompressionType { None, Gzip, } #[derive(De...
} }
_ => panic!("Invalid result: {:#?}", result), }
random_line_split
mod.rs
mod builder; mod master_key; mod tlv; use bytes; use decompress; use {Error, FileType}; use self::builder::HeaderBuilder; use protected::ProtectedStream; use std::io::Read; #[derive(Debug, PartialEq)] enum CipherType { Aes, } #[derive(Debug, PartialEq)] enum CompressionType { None, Gzip, } #[derive(De...
#[cfg(test)] mod test { use {Error, FileType}; #[test] pub fn should_return_error_if_wrong_file_type() { let result = super::read_header(FileType::KeePass1, &mut &vec![][..]); match result { Err(Error::UnsupportedFileType(FileType::KeePass1)) => (), _ => panic!("I...
{ let mut builder = HeaderBuilder::new(version); for tlv in tlv::tlvs(reader) { match tlv { Ok(t) => builder.apply(t), Err(e) => return Err(e), } } builder.build() }
identifier_body
data.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/. */ //! Data needed to style a Gecko document. use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use cont...
(AtomicRefCell<PerDocumentStyleDataImpl>); impl PerDocumentStyleData { /// Create a dummy `PerDocumentStyleData`. pub fn new(pres_context: RawGeckoPresContextOwned) -> Self { let device = Device::new(pres_context); // FIXME(emilio, tlin): How is this supposed to work with XBL? This is ...
PerDocumentStyleData
identifier_name
data.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/. */ //! Data needed to style a Gecko document. use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use cont...
impl PerDocumentStyleDataImpl { /// Recreate the style data if the stylesheets have changed. pub fn flush_stylesheets<E>( &mut self, guard: &SharedRwLockReadGuard, document_element: Option<E>, snapshots: Option<&SnapshotMap>, ) -> bool where E: TElement, { ...
random_line_split
data.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/. */ //! Data needed to style a Gecko document. use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use cont...
/// Measure heap usage. pub fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) { self.stylist.add_size_of(ops, sizes); } /// Record that a traversal happened for later collection as telemetry pub fn record_traversal(&self, was_parallel: bool, stats: Option<Tr...
{ if !self.visited_links_enabled() { return false; } if self.is_private_browsing_enabled() { return false; } if self.is_being_used_as_an_image() { return false; } true }
identifier_body
data.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/. */ //! Data needed to style a Gecko document. use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; use cont...
} } unsafe impl HasFFI for PerDocumentStyleData { type FFIType = RawServoStyleSet; } unsafe impl HasSimpleFFI for PerDocumentStyleData {} unsafe impl HasBoxFFI for PerDocumentStyleData {}
{ self.traversal_count_traversed.record(was_parallel, stats.elements_traversed); self.traversal_count_styled.record(was_parallel, stats.elements_styled); }
conditional_block
timestamp.rs
pub struct Timestamp(u64); pub trait InTimestampUnits { /// milliseconds fn ms(self) -> Timestamp; /// microseconds fn us(self) -> Timestamp; /// nanoseconds fn ns(self) -> Timestamp; } impl InTimestampUnits for f64 { fn ms(self) -> Timestamp { Timestamp((self * 1_000_000.0) as u...
}
{ Timestamp(self) }
identifier_body
timestamp.rs
pub struct Timestamp(u64); pub trait InTimestampUnits { /// milliseconds fn ms(self) -> Timestamp; /// microseconds fn us(self) -> Timestamp; /// nanoseconds fn ns(self) -> Timestamp; } impl InTimestampUnits for f64 { fn ms(self) -> Timestamp { Timestamp((self * 1_000_000.0) as u...
fn ms(self) -> Timestamp { Timestamp(self * 1_000_000u64) } fn us(self) -> Timestamp { Timestamp(self * 1_000u64) } fn ns(self) -> Timestamp { Timestamp(self) } }
random_line_split
timestamp.rs
pub struct Timestamp(u64); pub trait InTimestampUnits { /// milliseconds fn ms(self) -> Timestamp; /// microseconds fn us(self) -> Timestamp; /// nanoseconds fn ns(self) -> Timestamp; } impl InTimestampUnits for f64 { fn ms(self) -> Timestamp { Timestamp((self * 1_000_000.0) as u...
(self) -> Timestamp { Timestamp((self * 1_000.0) as u64) } fn ns(self) -> Timestamp { Timestamp(self as u64) } } impl InTimestampUnits for u64 { fn ms(self) -> Timestamp { Timestamp(self * 1_000_000u64) } fn us(self) -> Timestamp { Timestamp(self * 1_000u64) ...
us
identifier_name
issue-37945.rs
// compile-flags: -O -Zmerge-functions=disabled // ignore-x86 // ignore-arm // ignore-emscripten // ignore-gnux32 // ignore 32-bit platforms (LLVM has a bug with them) // Check that LLVM understands that `Iter` pointer is not null. Issue #37945. #![crate_type = "lib"] use std::slice::Iter; #[no_mangle] pub fn is_em...
#[no_mangle] pub fn is_empty_2(xs: Iter<f32>) -> bool { // CHECK-LABEL: @is_empty_2 // CHECK-NEXT: start: // CHECK-NEXT: [[C:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[C]]) // CHECK-NEXT: [[D:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[D:%.*]] xs.ma...
{ // CHECK-LABEL: @is_empty_1( // CHECK-NEXT: start: // CHECK-NEXT: [[A:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[A]]) // CHECK-NEXT: [[B:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[B:%.*]] {xs}.next().is_none() }
identifier_body
issue-37945.rs
// compile-flags: -O -Zmerge-functions=disabled // ignore-x86 // ignore-arm // ignore-emscripten // ignore-gnux32 // ignore 32-bit platforms (LLVM has a bug with them) // Check that LLVM understands that `Iter` pointer is not null. Issue #37945. #![crate_type = "lib"]
// CHECK-LABEL: @is_empty_1( // CHECK-NEXT: start: // CHECK-NEXT: [[A:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[A]]) // CHECK-NEXT: [[B:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[B:%.*]] {xs}.next().is_none() } #[no_mangle] pub fn is_empty_2(xs: It...
use std::slice::Iter; #[no_mangle] pub fn is_empty_1(xs: Iter<f32>) -> bool {
random_line_split
issue-37945.rs
// compile-flags: -O -Zmerge-functions=disabled // ignore-x86 // ignore-arm // ignore-emscripten // ignore-gnux32 // ignore 32-bit platforms (LLVM has a bug with them) // Check that LLVM understands that `Iter` pointer is not null. Issue #37945. #![crate_type = "lib"] use std::slice::Iter; #[no_mangle] pub fn
(xs: Iter<f32>) -> bool { // CHECK-LABEL: @is_empty_1( // CHECK-NEXT: start: // CHECK-NEXT: [[A:%.*]] = icmp ne i32* %xs.1, null // CHECK-NEXT: tail call void @llvm.assume(i1 [[A]]) // CHECK-NEXT: [[B:%.*]] = icmp eq i32* %xs.0, %xs.1 // CHECK-NEXT: ret i1 [[B:%.*]] {xs}.next().is_none() } #[no_mangle...
is_empty_1
identifier_name
worker.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 devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg}; use dom::bindings::codegen::Bindings::EventHa...
(global: GlobalRef, script_url: DOMString) -> Fallible<Root<Worker>> { // Step 2-4. let worker_url = match global.api_base_url().join(&script_url) { Ok(url) => url, Err(_) => return Err(Error::Syntax), }; let resource_thread = global.resource_thread(); le...
Constructor
identifier_name
worker.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 devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg}; use dom::bindings::codegen::Bindings::EventHa...
} // https://html.spec.whatwg.org/multipage/#terminate-a-worker fn Terminate(&self) { // Step 1 if self.closing.swap(true, Ordering::SeqCst) { return; } // Step 4 if let Some(runtime) = *self.runtime.lock().unwrap() { runtime.request_interrup...
let address = Trusted::new(self); self.sender.send((address, WorkerScriptMsg::DOMMessage(data))).unwrap(); Ok(())
random_line_split
relm-root.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
} } fn main() { Win::run(()).expect("Win::run failed"); } #[cfg(test)] mod tests { use gtk::{Button, Label, prelude::WidgetExt}; use gtk_test::find_child_by_name; use crate::Win; #[test] fn root_widget() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_te...
type Widgets = Widgets; fn get_widgets(&self) -> Self::Widgets { self.widgets.clone()
random_line_split
relm-root.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
{ _components: Components, widgets: Widgets, } impl Update for Win { type Model = (); type ModelParam = (); type Msg = Msg; fn model(_: &Relm<Self>, _: ()) -> () { } fn update(&mut self, event: Msg) { match event { Quit => gtk::main_quit(), } } } impl...
Win
identifier_name
relm-root.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
fn view(relm: &Relm<Self>, _model: Self::Model) -> Self { let window = Window::new(WindowType::Toplevel); let vbox = window.add_widget::<MyVBox>(()); window.show_all(); connect!(relm, window, connect_delete_event(_, _), return (Some(Msg::Quit), Inhibit(false))); Win { ...
{ self.widgets.window.clone() }
identifier_body
main.rs
extern crate docopt; extern crate libc; #[cfg(feature = "re-pcre1")] extern crate libpcre_sys; extern crate memmap; #[cfg(feature = "re-onig")] extern crate onig; #[cfg(any(feature = "re-rust", feature = "re-rust-bytes",))] extern crate regex; #[cfg(feature = "re-rust")] extern crate regex_syntax; extern crate serde; #...
(pat: &str, haystack: &str) -> usize { use regex::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() } nada!("re-rust-bytes", count_rust_bytes); #[cfg(feature = "re-rust-bytes")] fn count_rust_bytes(pat: &str, haystack: &str) -> usize { use regex::bytes::Regex; Regex::new(pat).unwrap().find_it...
count_rust
identifier_name
main.rs
extern crate docopt; extern crate libc; #[cfg(feature = "re-pcre1")] extern crate libpcre_sys; extern crate memmap; #[cfg(feature = "re-onig")] extern crate onig; #[cfg(any(feature = "re-rust", feature = "re-rust-bytes",))] extern crate regex; #[cfg(feature = "re-rust")] extern crate regex_syntax; extern crate serde; #...
nada!("re-rust-bytes", count_rust_bytes); #[cfg(feature = "re-rust-bytes")] fn count_rust_bytes(pat: &str, haystack: &str) -> usize { use regex::bytes::Regex; Regex::new(pat).unwrap().find_iter(haystack.as_bytes()).count() } nada!("re-tcl", count_tcl); #[cfg(feature = "re-tcl")] fn count_tcl(pat: &str, hayst...
{ use regex::Regex; Regex::new(pat).unwrap().find_iter(haystack).count() }
identifier_body
main.rs
extern crate docopt; extern crate libc; #[cfg(feature = "re-pcre1")] extern crate libpcre_sys;
#[cfg(any(feature = "re-rust", feature = "re-rust-bytes",))] extern crate regex; #[cfg(feature = "re-rust")] extern crate regex_syntax; extern crate serde; #[macro_use] extern crate serde_derive; use std::fs::File; use std::str; use docopt::Docopt; use memmap::Mmap; mod ffi; const USAGE: &'static str = " Count the ...
extern crate memmap; #[cfg(feature = "re-onig")] extern crate onig;
random_line_split
scan.rs
use std::fs; use std::io; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; pub struct Scandir { pub path: PathBuf, pub interval: u64, } impl Scandir { pub fn new(dir: &str, seconds: u64) -> Result<Scandir, io::Error> { let path = try!(fs::canonicalize(dir)); Ok( S...
Ok(f) => f }; for f in files { let file = f.unwrap(); let mode = file.metadata().unwrap().permissions().mode(); let mut is_exec: bool = false; if!file.file_type().unwrap().is_dir() { is_exec = mode & 0o111!= 0; } ...
{ println!("{}", f); return; }
conditional_block
scan.rs
use std::fs; use std::io; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; pub struct Scandir { pub path: PathBuf, pub interval: u64, } impl Scandir { pub fn new(dir: &str, seconds: u64) -> Result<Scandir, io::Error> { let path = try!(fs::canonicalize(dir)); Ok( S...
(&self) { let files = match fs::read_dir(&self.path) { Err(f) => { println!("{}", f); return; } Ok(f) => f }; for f in files { let file = f.unwrap(); let mode = file.metadata().unwrap().permissions().mod...
scan
identifier_name
scan.rs
use std::fs; use std::io; use std::os::unix::fs::PermissionsExt; use std::path::PathBuf; pub struct Scandir {
impl Scandir { pub fn new(dir: &str, seconds: u64) -> Result<Scandir, io::Error> { let path = try!(fs::canonicalize(dir)); Ok( Scandir { path: path, interval: seconds } ) } pub fn scan(&self) { let files = match fs::r...
pub path: PathBuf, pub interval: u64, }
random_line_split
issue-17734.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} fn main() { // There is currently no safe way to construct a `Box<str>`, so improvise let box_arr: Box<[u8]> = box ['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8]; let box_str: Box<str> = unsafe { std::mem::transmute(box_arr) }; assert_eq!(&*box_str, "hello"); f(box_str); }
random_line_split
issue-17734.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ // There is currently no safe way to construct a `Box<str>`, so improvise let box_arr: Box<[u8]> = box ['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8]; let box_str: Box<str> = unsafe { std::mem::transmute(box_arr) }; assert_eq!(&*box_str, "hello"); f(box_str); }
identifier_body
issue-17734.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { // There is currently no safe way to construct a `Box<str>`, so improvise let box_arr: Box<[u8]> = box ['h' as u8, 'e' as u8, 'l' as u8, 'l' as u8, 'o' as u8]; let box_str: Box<str> = unsafe { std::mem::transmute(box_arr) }; assert_eq!(&*box_str, "hello"); f(box_str); }
main
identifier_name
mod.rs
// Copyright 2015 © Samuel Dolt <samuel@dolt.ch> // // This file is part of orion_backend. // // Orion_backend 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 ...
pub use self::device::Device; mod measurement; pub use self::measurement::Measurement; pub use self::measurement::ParseMeasurementError; mod measurements_list; pub use self::measurements_list::MeasurementsList; pub use self::measurements_list::ParseMeasurementsListError;
mod device;
random_line_split
ison.rs
use std::fmt; use protocol::command::CMD_ISON; use protocol::message::{IrcMessage, MessageParamIter, RawMessage, ParseMessageError, ParseMessageErrorKind}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct
<'a> { nicknames: &'a str, } impl<'a> IsonCommand<'a> { pub fn new(nicknames: &'a str) -> IsonCommand<'a> { IsonCommand { nicknames: nicknames, } } pub fn nicknames(&self) -> MessageParamIter<'a> { MessageParamIter::wrap(self.nicknames) } } impl<'a> fmt::Displa...
IsonCommand
identifier_name
ison.rs
#[derive(Debug, Clone, Eq, PartialEq)] pub struct IsonCommand<'a> { nicknames: &'a str, } impl<'a> IsonCommand<'a> { pub fn new(nicknames: &'a str) -> IsonCommand<'a> { IsonCommand { nicknames: nicknames, } } pub fn nicknames(&self) -> MessageParamIter<'a> { Messag...
use std::fmt; use protocol::command::CMD_ISON; use protocol::message::{IrcMessage, MessageParamIter, RawMessage, ParseMessageError, ParseMessageErrorKind};
random_line_split
ison.rs
use std::fmt; use protocol::command::CMD_ISON; use protocol::message::{IrcMessage, MessageParamIter, RawMessage, ParseMessageError, ParseMessageErrorKind}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct IsonCommand<'a> { nicknames: &'a str, } impl<'a> IsonCommand<'a> { pub fn new(nicknames: &'a str) -> Is...
Ok(IsonCommand::new(nicknames)) } }
{ return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams, "ISON requires at least one nickname")); }
conditional_block
ison.rs
use std::fmt; use protocol::command::CMD_ISON; use protocol::message::{IrcMessage, MessageParamIter, RawMessage, ParseMessageError, ParseMessageErrorKind}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct IsonCommand<'a> { nicknames: &'a str, } impl<'a> IsonCommand<'a> { pub fn new(nicknames: &'a str) -> Is...
} impl<'a> IrcMessage<'a> for IsonCommand<'a> { fn from_raw(raw: &RawMessage<'a>) -> Result<IsonCommand<'a>, ParseMessageError> { let nicknames = raw.parameters().get(); if nicknames.is_empty() { return Err(ParseMessageError::new(ParseMessageErrorKind::NeedMoreParams, ...
{ write!(f, "{} {}", CMD_ISON, self.nicknames) }
identifier_body
point_segment.rs
use na::Transform; use na; use entities::shape::Segment; use point::PointQuery; use math::{Scalar, Point, Vect}; impl<P, M> PointQuery<P, M> for Segment<P> where P: Point, M: Transform<P> { #[inline] fn project_point(&self, m: &M, pt: &P, _: bool) -> P { let ls_pt = m.inv_transform(pt); ...
elf, m: &M, pt: &P) -> <P::Vect as Vect>::Scalar { na::dist(pt, &self.project_point(m, pt, true)) } #[inline] fn contains_point(&self, m: &M, pt: &P) -> bool { na::approx_eq(&self.distance_to_point(m, pt), &na::zero()) } }
tance_to_point(&s
identifier_name
point_segment.rs
use na::Transform; use na; use entities::shape::Segment; use point::PointQuery; use math::{Scalar, Point, Vect}; impl<P, M> PointQuery<P, M> for Segment<P> where P: Point, M: Transform<P> { #[inline] fn project_point(&self, m: &M, pt: &P, _: bool) -> P { let ls_pt = m.inv_transform(pt); ...
#[inline] fn distance_to_point(&self, m: &M, pt: &P) -> <P::Vect as Vect>::Scalar { na::dist(pt, &self.project_point(m, pt, true)) } #[inline] fn contains_point(&self, m: &M, pt: &P) -> bool { na::approx_eq(&self.distance_to_point(m, pt), &na::zero()) } }
random_line_split
point_segment.rs
use na::Transform; use na; use entities::shape::Segment; use point::PointQuery; use math::{Scalar, Point, Vect}; impl<P, M> PointQuery<P, M> for Segment<P> where P: Point, M: Transform<P> { #[inline] fn project_point(&self, m: &M, pt: &P, _: bool) -> P
} #[inline] fn distance_to_point(&self, m: &M, pt: &P) -> <P::Vect as Vect>::Scalar { na::dist(pt, &self.project_point(m, pt, true)) } #[inline] fn contains_point(&self, m: &M, pt: &P) -> bool { na::approx_eq(&self.distance_to_point(m, pt), &na::zero()) } }
{ let ls_pt = m.inv_transform(pt); let ab = *self.b() - *self.a(); let ap = ls_pt - *self.a(); let ab_ap = na::dot(&ab, &ap); let sqnab = na::sqnorm(&ab); if ab_ap <= na::zero() { // voronoï region of vertex 'a'. m.transform(self.a()) ...
identifier_body
main.rs
#![feature(plugin)] #![feature(test)] #![plugin(peg_syntax_ext)] #[macro_use] extern crate nom; extern crate clap; extern crate termion; extern crate byteorder; extern crate env_logger; extern crate vec_map; extern crate tempdir; #[macro_use] extern crate log; mod db; use db::server::Server; use db::database::{Da...
, Err(e) => {} } } }
{}
conditional_block
main.rs
#![feature(plugin)] #![feature(test)] #![plugin(peg_syntax_ext)] #[macro_use] extern crate nom; extern crate clap; extern crate termion; extern crate byteorder; extern crate env_logger; extern crate vec_map; extern crate tempdir; #[macro_use] extern crate log; mod db; use db::server::Server; use db::database::{Da...
fn run_test_repl() { let _ = env_logger::init(); println!("Running test repl"); // use local dir "dbs" let dbdir = "trdb"; if let Err(x) = fs::create_dir(dbdir) { warn!("Error creating directory {}", x); } let mut db = Database::new(PathBuf::from(dbdir)); let mut stdin = stdin(...
{ println!("Starting the worst database ever created!! (exit to exit)"); let server = Server::new(); let app = App::new("TotalRecallDB") .version("v1.0") .author("Jon Haddad, <jon@jonhaddad.com>") .subcommand(SubCommand::with_name("test")) ...
identifier_body
main.rs
#![feature(plugin)] #![feature(test)] #![plugin(peg_syntax_ext)] #[macro_use] extern crate nom; extern crate clap; extern crate termion; extern crate byteorder; extern crate env_logger; extern crate vec_map; extern crate tempdir; #[macro_use] extern crate log; mod db; use db::server::Server; use db::database::{Da...
() { let _ = env_logger::init(); println!("Running test repl"); // use local dir "dbs" let dbdir = "trdb"; if let Err(x) = fs::create_dir(dbdir) { warn!("Error creating directory {}", x); } let mut db = Database::new(PathBuf::from(dbdir)); let mut stdin = stdin(); let mut std...
run_test_repl
identifier_name
main.rs
#![feature(plugin)] #![feature(test)] #![plugin(peg_syntax_ext)] #[macro_use] extern crate nom; extern crate clap; extern crate termion; extern crate byteorder; extern crate env_logger; extern crate vec_map; extern crate tempdir; #[macro_use] extern crate log; mod db; use db::server::Server; use db::database::{Da...
}; println!("{}", x); }, Ok(None) => {}, Err(e) => {} } } }
format!("Inserted {}", id), _ => String::from("Fail?")
random_line_split
raft_engine_switch.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crossbeam::channel::{unbounded, Receiver}; use engine_rocks::{self, raw::Env, RocksEngine}; use engine_traits::{ CompactExt, DeleteStrategy, Error as EngineError, Iterable, Iterator, MiscExt, RaftEngine, RaftLogBatch, Range, SeekKey, }; use...
info!("Scanned all region id and waiting for dump"); for t in threads { t.join().unwrap(); } engine.sync().unwrap(); info!( "Finished dump, total regions: {}; Total bytes: {}; Consumed time: {:?}", count_region, count_size.load(Ordering::Relaxed), consumed_ti...
drop(tx);
random_line_split
raft_engine_switch.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crossbeam::channel::{unbounded, Receiver}; use engine_rocks::{self, raw::Env, RocksEngine}; use engine_traits::{ CompactExt, DeleteStrategy, Error as EngineError, Iterable, Iterator, MiscExt, RaftEngine, RaftLogBatch, Range, SeekKey, }; use...
(path: &str) -> PathBuf { let mut flag_path = PathBuf::from(path); flag_path.set_extension("REMOVE"); flag_path } fn remove_tmp_dir<P: AsRef<Path>>(dir: P) { match delete_dir_if_exist(&dir) { Err(e) => warn!("Cannot remove {:?}: {}", dir.as_ref(), e), Ok(true) => info!("Remove {:?} succ...
get_path_for_remove
identifier_name
raft_engine_switch.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crossbeam::channel::{unbounded, Receiver}; use engine_rocks::{self, raw::Env, RocksEngine}; use engine_traits::{ CompactExt, DeleteStrategy, Error as EngineError, Iterable, Iterator, MiscExt, RaftEngine, RaftLogBatch, Range, SeekKey, }; use...
// Insert some data into log batch. fn set_write_batch<T: RaftLogBatch>(num: u64, batch: &mut T) { let mut state = RaftLocalState::default(); state.set_last_index(num); batch.put_raft_state(num, &state).unwrap(); let mut entries = vec![]; for i in 0..num { l...
{ do_test_switch(false, true); }
identifier_body
raft_engine_switch.rs
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0. use crossbeam::channel::{unbounded, Receiver}; use engine_rocks::{self, raw::Env, RocksEngine}; use engine_traits::{ CompactExt, DeleteStrategy, Error as EngineError, Iterable, Iterator, MiscExt, RaftEngine, RaftLogBatch, Range, SeekKey, }; use...
// Clean the target engine if it exists. clear_raft_engine(engine).expect("clear_raft_engine"); let config_raftdb = &config.raftdb; let mut raft_db_opts = config_raftdb.build_opt(); raft_db_opts.set_env(env.clone()); let raft_db_cf_opts = config_raftdb.build_cf_opts(&None); let db = engin...
{ remove_tmp_dir(&dirty_raftdb_path); return; }
conditional_block