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
mergeable.rs
use fnv::FnvHasher; use std::cmp::max; use std::collections::HashMap; use std::collections::hash_map::Iter; use std::hash::BuildHasherDefault; use std::ops::AddAssign; use std::sync::{Arc, RwLock, RwLockReadGuard}; use utils::Flow; /// A generic store for associating some merge-able type with each flow. Note, the me...
(&self) -> bool { self.len!= 0 } }
is_empty
identifier_name
mergeable.rs
use fnv::FnvHasher; use std::cmp::max; use std::collections::HashMap; use std::collections::hash_map::Iter; use std::hash::BuildHasherDefault; use std::ops::AddAssign; use std::sync::{Arc, RwLock, RwLockReadGuard}; use utils::Flow; /// A generic store for associating some merge-able type with each flow. Note, the me...
/// Remove an entry from the table. #[inline] pub fn remove(&mut self, flow: &Flow) -> T { // self.merge_cache(); match self.flow_counters.write() { Ok(mut g) => { g.extend(self.cache.drain(0..)); self.cache_size = self.base_cache_size; ...
{ { self.cache.push((flow, inc)); } if self.cache.len() >= self.cache_size { self.merge_cache(); } }
identifier_body
mergeable.rs
use fnv::FnvHasher; use std::cmp::max; use std::collections::HashMap; use std::collections::hash_map::Iter; use std::hash::BuildHasherDefault; use std::ops::AddAssign; use std::sync::{Arc, RwLock, RwLockReadGuard}; use utils::Flow; /// A generic store for associating some merge-able type with each flow. Note, the me...
} /// Remove an entry from the table. #[inline] pub fn remove(&mut self, flow: &Flow) -> T { // self.merge_cache(); match self.flow_counters.write() { Ok(mut g) => { g.extend(self.cache.drain(0..)); self.cache_size = self.base_cache_size; ...
{ self.merge_cache(); }
conditional_block
mergeable.rs
use fnv::FnvHasher; use std::cmp::max; use std::collections::HashMap; use std::collections::hash_map::Iter; use std::hash::BuildHasherDefault; use std::ops::AddAssign; use std::sync::{Arc, RwLock, RwLockReadGuard}; use utils::Flow; /// A generic store for associating some merge-able type with each flow. Note, the me...
len: 0, } } pub fn dp_store(&mut self) -> MergeableStoreDP<T> { MergeableStoreCP::dp_store_with_cache_and_size(self, CACHE_SIZE, VEC_SIZE) } fn hmap_to_vec(hash: &RwLockReadGuard<HashMap<Flow, T, FnvHash>>) -> Vec<(Flow, T)> { let mut t = Vec::with_capacity(hash.len...
base_cache_size: cache,
random_line_split
spanmap.rs
use system::*; use span::Span; use objectheap::StaticObjectHeap; // Addressing bits: 48 // Page bits: 48 - 12 = 36 // 36 / 3: 12 pub const INDEX_BITS: usize = 12; pub const INDEX_SIZE: usize = 1 << INDEX_BITS; struct SpanMapLevel1 { pml: [usize; INDEX_SIZE], } struct SpanMapLevel2 { pml: [*mut SpanMapLevel...
{ pml3: SpanMapLevel3, } static mut PML2_ALLOCATOR: StaticObjectHeap<SpanMapLevel2> = StaticObjectHeap::new(); static mut PML1_ALLOCATOR: StaticObjectHeap<SpanMapLevel1> = StaticObjectHeap::new(); #[inline] fn indices_from_address(uptr: usize) -> (usize, usize, usize) { let pml1i = (uptr >> PAGE_BITS) & 0xff...
SpanMap
identifier_name
spanmap.rs
use system::*; use span::Span; use objectheap::StaticObjectHeap; // Addressing bits: 48 // Page bits: 48 - 12 = 36 // 36 / 3: 12 pub const INDEX_BITS: usize = 12; pub const INDEX_SIZE: usize = 1 << INDEX_BITS; struct SpanMapLevel1 { pml: [usize; INDEX_SIZE], } struct SpanMapLevel2 { pml: [*mut SpanMapLevel...
libc::pthread_mutex_unlock(&mut SPANMAP_MUTEX); r as *mut Span } } pub fn set_span(ptr: usize, value: *mut Span) { unsafe { libc::pthread_mutex_lock(&mut SPANMAP_MUTEX); SPANMAP.set_span(ptr, value as usize); libc::pthread_mutex_unlock(&mut SPANMAP_MUTEX); } } #[cf...
libc::pthread_mutex_lock(&mut SPANMAP_MUTEX); let r = SPANMAP.span(ptr);
random_line_split
spanmap.rs
use system::*; use span::Span; use objectheap::StaticObjectHeap; // Addressing bits: 48 // Page bits: 48 - 12 = 36 // 36 / 3: 12 pub const INDEX_BITS: usize = 12; pub const INDEX_SIZE: usize = 1 << INDEX_BITS; struct SpanMapLevel1 { pml: [usize; INDEX_SIZE], } struct SpanMapLevel2 { pml: [*mut SpanMapLevel...
} 0 } } pub fn set_span(&mut self, ptr: usize, value: usize) { self.ensure(ptr, 0); let (pml3i, pml2i, pml1i) = indices_from_address(ptr); unsafe { (*(*self.pml3.pml[pml3i]).pml[pml2i]).pml[pml1i] = value; } } } extern crate libc...
{ return (*l1).pml[pml1i]; }
conditional_block
main.rs
extern crate piston; extern crate graphics; extern crate opengl_graphics; extern crate piston_window; use std::io; use std::io::prelude::*; use piston_window::*; use opengl_graphics::{ GlGraphics }; pub struct Display{ gl: GlGraphics, should_redraw: bool, clear_colour: [f32; 4], cursor_position: (f64, f64) }...
pub fn move_cursor(&mut self, x: f64, y: f64){ self.cursor_position = (x,y); self.should_redraw = true; } pub fn update(&mut self, args:UpdateArgs){ //self.should_redraw = true; } } fn main() { let opengl = OpenGL::V3_2; //Why V?! http://www.rust-ci.org/PistonDevelopers/piston/doc/shader_versi...
{ const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; let square = rectangle::square(self.cursor_position.0, self.cursor_position.1, 50.0); let borrowed_colour = self.clear_colour; self.gl.draw(args.viewport(), |_c, g| { clear(borrowed_colour, g); rectangle(RED, square, _c.transform, g); }); ...
identifier_body
main.rs
extern crate piston; extern crate graphics; extern crate opengl_graphics; extern crate piston_window; use std::io; use std::io::prelude::*; use piston_window::*; use opengl_graphics::{ GlGraphics }; pub struct Display{ gl: GlGraphics, should_redraw: bool, clear_colour: [f32; 4], cursor_position: (f64, f64) }...
} _ => {} } } } } /* initialize shit Fetch events. Pass events to handling thread. (Put events in FIFO queue?) Can't acces glContext directly, can change cpu-side state and flag for bufferswap. swap buffers (if neccesary). */ /* -Mouse tracking lags behind...
window.set_should_close(true); }
random_line_split
main.rs
extern crate piston; extern crate graphics; extern crate opengl_graphics; extern crate piston_window; use std::io; use std::io::prelude::*; use piston_window::*; use opengl_graphics::{ GlGraphics }; pub struct
{ gl: GlGraphics, should_redraw: bool, clear_colour: [f32; 4], cursor_position: (f64, f64) } impl Display{ pub fn new(gl_version: OpenGL) -> Self{ Display{ should_redraw: true, gl: GlGraphics::new(gl_version), clear_colour: [1f32;4], cursor_position: (0.0, 0.0) } } pub f...
Display
identifier_name
tab.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/. */ /// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d...
#[deriving(Encodable)] struct FrameMsg { id: uint, url: String, title: String, parentID: uint, } #[deriving(Encodable)] pub struct TabActorMsg { actor: String, title: String, url: String, outerWindowID: uint, consoleActor: String, inspectorActor: String, } pub struct TabActor ...
frames: Vec<FrameMsg>, }
random_line_split
tab.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/. */ /// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d...
_ => false }) } } impl TabActor { pub fn encodable(&self) -> TabActorMsg { TabActorMsg { actor: self.name(), title: self.title.clone(), url: self.url.clone(), outerWindowID: 0, //FIXME: this should probably be the pipeline id ...
{ let msg = ListFramesReply { from: self.name(), frames: vec!(), }; stream.write_json_packet(&msg); true }
conditional_block
tab.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/. */ /// Liberally derived from the [Firefox JS implementation](http://mxr.mozilla.org/mozilla-central/source/toolkit/d...
{ from: String } #[deriving(Encodable)] struct ListFramesReply { from: String, frames: Vec<FrameMsg>, } #[deriving(Encodable)] struct FrameMsg { id: uint, url: String, title: String, parentID: uint, } #[deriving(Encodable)] pub struct TabActorMsg { actor: String, title: String, ...
ReconfigureReply
identifier_name
http_loader.rs
::new(CookieStorage::new())), auth_cache: Arc::new(RwLock::new(HashMap::new())), } } } fn load_for_consumer(load_data: LoadData, start_chan: LoadConsumer, classifier: Arc<MIMEClassifier>, connector: Arc<Pool<Connector>>, ...
fn auth_from_entry(auth_entry: &AuthCacheEntry, headers: &mut Headers) { let user_name = auth_entry.user_name.clone(); let password = Some(auth_entry.password.clone()); headers.set(Authorization(Basic { username: user_name, password: password })); } fn auth_from_url(doc_url: &Url) -> Option<Authorizati...
{ if !headers.has::<Authorization<Basic>>() { if let Some(auth) = auth_from_url(url) { headers.set(auth); } else { if let Some(ref auth_entry) = auth_cache.read().unwrap().get(url) { auth_from_entry(&auth_entry, headers); } } } }
identifier_body
http_loader.rs
impl<R: HttpResponse> StreamedResponse<R> { fn new(m: Metadata, d: Decoder<R>) -> StreamedResponse<R> { StreamedResponse { metadata: m, decoder: d } } fn from_http_response(response: R, m: Metadata) -> Result<StreamedResponse<R>, LoadError> { match response.content_encoding() { ...
is_cert_verify_error
identifier_name
http_loader.rs
fn set_cookie_for_url(cookie_jar: &Arc<RwLock<CookieStorage>>, request: Url, cookie_val: String) { let mut cookie_jar = cookie_jar.write().unwrap(); let source = CookieSource::HTTP; let header = Header::parse_header(&[cookie_val.into_bytes()]); if let Ok(SetC...
let mut adjusted_headers = response.headers().clone(); if viewing_source {
random_line_split
tests.rs
// #![deny(warnings)] #![deny(bad_style)] #[macro_use] extern crate rustless; extern crate hyper; extern crate rustc_serialize as serialize; extern crate url; extern crate valico; extern crate jsonway; #[macro_export] macro_rules! sr { ($method:ident, $url:expr) => { ::rustless::SimpleRequest::new(::rustl...
$resp.read_to_end(&mut bytes).unwrap(); String::from_utf8(bytes).unwrap() } } } #[macro_export] macro_rules! mime { ($mime:expr) => ($mime.parse().unwrap()) } macro_rules! app { ($builder:expr) => ({ let app = ::rustless::Application::new(::rustless::Api::build($bui...
($resp:ident) => { { use std::io::Read; let mut bytes = Vec::new();
random_line_split
mod.rs
pub mod types; pub mod utils; pub mod connection; pub mod init; use futures::{ Future, Stream, Sink }; use futures::sync::mpsc::UnboundedSender; use futures::sync::oneshot::{ Sender as OneshotSender, channel as oneshot_channel }; use crate::utils as client_utils; use std::ops::{ Deref, DerefMut }; us...
/// Send a command to the Redis server(s). pub fn write_command(&self, inner: &Arc<RedisClientInner>, request: &mut RedisCommand) -> Box<Future<Item=(), Error=RedisError>> { trace!("{} Multiplexer sending command {:?}", n!(inner), request.kind); if request.attempted > 0 { client_utils::incr_atomic(&...
{ utils::take_last_request(&self.last_request_sent, &self.inner, &self.last_request) }
identifier_body
mod.rs
pub mod types; pub mod utils; pub mod connection; pub mod init; use futures::{ Future, Stream, Sink }; use futures::sync::mpsc::UnboundedSender; use futures::sync::oneshot::{ Sender as OneshotSender, channel as oneshot_channel }; use crate::utils as client_utils; use std::ops::{ Deref, DerefMut }; use...
use crate::protocol::types::{RedisCommand, ClusterKeyCache, RedisCommandKind}; use std::fmt; use std::rc::Rc; use std::cell::RefCell; use std::collections::{ BTreeMap, VecDeque }; use crate::protocol::types::ResponseSender; use crate::client::RedisClientInner; use crate::multiplexer::types::{ Streams, Sinks ...
RedisKey, ClientState };
random_line_split
mod.rs
pub mod types; pub mod utils; pub mod connection; pub mod init; use futures::{ Future, Stream, Sink }; use futures::sync::mpsc::UnboundedSender; use futures::sync::oneshot::{ Sender as OneshotSender, channel as oneshot_channel }; use crate::utils as client_utils; use std::ops::{ Deref, DerefMut }; us...
(&self) -> Option<LastCommandCaller> { utils::take_last_command_callback(&self.last_command_callback) } pub fn set_last_request(&self, cmd: Option<RedisCommand>) { utils::set_option(&self.last_request_sent, Some(Instant::now())); utils::set_option(&self.last_request, cmd); } pub fn take_last_reque...
take_last_command_callback
identifier_name
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
if width <= 64 { format!("bigint::prelude::U256::from({} as u64)", name) } else { format!("bigint::prelude::U256::from({})", name) } ), ParamType::Bool => format!("Token::Bool({})", name), ParamType::String => format!("Token::String({})", name), ParamType::Array(kind) => { let (needs_mut, code) = token...
{ let mut needs_mut = false; let code = match input { ParamType::Address => format!("Token::Address({}.0)", name), ParamType::Bytes => format!("Token::Bytes({})", name), ParamType::FixedBytes(len) if len <= 32 => format!("Token::FixedBytes({}.0.to_vec())", name), ParamType::FixedBytes(len) => { needs_mu...
identifier_body
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} output_type.push_str(")"); decode_outputs.push_str("))"); Ok((output_type, decode_outputs)) } // create code for an argument type from param type. fn rust_type(input: ParamType) -> Result<String, ParamType> { Ok(match input { ParamType::Address => "bigint::prelude::H160".into(), ParamType::FixedBytes(len)...
{ output_type.push_str(", "); decode_outputs.push_str(", "); }
conditional_block
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
output_type.push_str(")"); decode_outputs.push_str("))"); Ok((output_type, decode_outputs)) } // create code for an argument type from param type. fn rust_type(input: ParamType) -> Result<String, ParamType> { Ok(match input { ParamType::Address => "bigint::prelude::H160".into(), ParamType::FixedBytes(len) if l...
output_type.push_str(", "); decode_outputs.push_str(", "); } }
random_line_split
lib.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
() { assert_eq!(::output_params_codegen(&[]).unwrap().0, "()"); assert_eq!(::output_params_codegen(&[ParamType::Address]).unwrap().0, "(bigint::prelude::H160)"); assert_eq!(::output_params_codegen(&[ParamType::Address, ParamType::Array(Box::new(ParamType::Bytes))]).unwrap().0, "(bigint::prelude::H160, Vec<Vec<...
output_types
identifier_name
internal-unstable.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 ...
{ // ok, the instability is contained. call_unstable_allow!(); construct_unstable_allow!(0); // bad. pass_through_allow!(internal_unstable::unstable()); //~ ERROR use of unstable pass_through_noallow!(internal_unstable::unstable()); //~ ERROR use of unstable println!("{:?}", internal_un...
identifier_body
internal-unstable.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 ...
$f; internal_unstable::unstable(); //~ ERROR use of unstable }} } #[allow_internal_unstable] macro_rules! bar { ($e: expr) => {{ foo!($e, internal_unstable::unstable()); internal_unstable::unstable(); }} } fn main() { // ok, the instability is contained. ...
($e: expr, $f: expr) => {{ $e;
random_line_split
internal-unstable.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 ...
() { // ok, the instability is contained. call_unstable_allow!(); construct_unstable_allow!(0); // bad. pass_through_allow!(internal_unstable::unstable()); //~ ERROR use of unstable pass_through_noallow!(internal_unstable::unstable()); //~ ERROR use of unstable println!("{:?}", internal...
main
identifier_name
struct_variant_xc_match.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ let arg = match (StructVariant { arg: 42 }) { Variant(_) => unreachable!(), StructVariant { arg } => arg }; assert_eq!(arg, 42); }
identifier_body
struct_variant_xc_match.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let arg = match (StructVariant { arg: 42 }) { Variant(_) => unreachable!(), StructVariant { arg } => arg }; assert_eq!(arg, 42); }
main
identifier_name
struct_variant_xc_match.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn main() { let arg = match (StructVariant { arg: 42 }) { Variant(_) => unreachable!(), StructVariant { arg } => arg }; assert_eq!(arg, 42); }
use struct_variant_xc_aux::Enum::{StructVariant, Variant};
random_line_split
inflating_cryptocurrency.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
(self, amount: u64, height: Height) -> Self { let balance = self.actual_balance(height) - amount; Self::new(&self.pub_key, &self.name, balance, height.0) } } // // // // // // // // // // DATA LAYOUT // // // // // // // // // // #[derive(FromAccess)] pub(crate) struct CurrencySchema<T: Access> { ...
decrease
identifier_name
inflating_cryptocurrency.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
fn transfer(&self, ctx: ExecutionContext<'_>, arg: Transfer) -> Self::Output { let author = ctx.caller().author().unwrap(); if author == arg.to { return Err(Error::SenderSameAsReceiver.into()); } let height = ctx.data().for_core().height(); let mut schema = Cur...
{ let author = ctx.caller().author().unwrap(); let height = ctx.data().for_core().height(); let mut schema = CurrencySchema::new(ctx.service_data()); if schema.wallet(&author).is_none() { let wallet = Wallet::new(&author, &arg.name, INIT_BALANCE, height.0); schem...
identifier_body
inflating_cryptocurrency.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
impl DefaultInstance for CurrencyService { const INSTANCE_ID: u32 = SERVICE_ID; const INSTANCE_NAME: &'static str = SERVICE_NAME; }
fn wire_api(&self, builder: &mut ServiceApiBuilder) { CryptocurrencyApi::wire(builder) } }
random_line_split
inflating_cryptocurrency.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
} Ok(()) } } // // // // // // // // // // REST API // // // // // // // // // // struct CryptocurrencyApi; #[derive(Debug, Serialize, Deserialize)] struct BalanceQuery { pub_key: PublicKey, } /// Shortcut to get data on wallets. impl CryptocurrencyApi { /// Endpoint for retrieving a si...
{ let sender = sender.decrease(amount, height); let receiver = receiver.increase(amount, height); schema.wallets.put(&author, sender); schema.wallets.put(&arg.to, receiver); }
conditional_block
csum.rs
/// TCP & IP checksums implementations /// actual checksumming is delegated to optimized /// C routines extracted from linux kernel // TODO: rewrite in rust use std::net::Ipv4Addr; use pnet::packet::Packet; use pnet::packet::ip::{IpNextHeaderProtocol}; use pnet::packet::ipv4::Ipv4Packet; use pnet::packet::tcp::TcpPack...
{ use pnet::packet::Packet; let len = packet.get_header_length() as u32 * 4; let bytes = packet.packet(); unsafe { ip_compute_csum(bytes.as_ptr(), len) } }
identifier_body
csum.rs
/// TCP & IP checksums implementations /// actual checksumming is delegated to optimized /// C routines extracted from linux kernel // TODO: rewrite in rust use std::net::Ipv4Addr; use pnet::packet::Packet; use pnet::packet::ip::{IpNextHeaderProtocol}; use pnet::packet::ipv4::Ipv4Packet; use pnet::packet::tcp::TcpPack...
(packet: &Ipv4Packet) -> u16 { use pnet::packet::Packet; let len = packet.get_header_length() as u32 * 4; let bytes = packet.packet(); unsafe { ip_compute_csum(bytes.as_ptr(), len) } }
ip_checksum
identifier_name
csum.rs
/// TCP & IP checksums implementations /// actual checksumming is delegated to optimized /// C routines extracted from linux kernel // TODO: rewrite in rust use std::net::Ipv4Addr; use pnet::packet::Packet; use pnet::packet::ip::{IpNextHeaderProtocol}; use pnet::packet::ipv4::Ipv4Packet; use pnet::packet::tcp::TcpPack...
let octets = ipv4_destination.octets(); sum += ((octets[0] as u16) << 8 | (octets[1] as u16)) as u32; sum += ((octets[2] as u16) << 8 | (octets[3] as u16)) as u32; sum += next_level_protocol as u32; let bytes = packet.packet(); let len = bytes.len() as u32; sum += len; unsafe { csum_pa...
random_line_split
headers.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMe...
} None } // http://tools.ietf.org/html/rfc7230#section-3.2 fn is_field_name(name: &ByteString) -> bool { is_token(&*name) } // https://tools.ietf.org/html/rfc7230#section-3.2 // http://www.rfc-editor.org/errata_search.php?rfc=7230 // Errata ID: 4189 // field-content = field-vchar [ 1*( SP / HTAB / field-...
{ return Some(index); }
conditional_block
headers.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMe...
(x: u8) -> bool { match x { 0x80...0xFF => true, _ => false, } }
is_obs_text
identifier_name
headers.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMe...
return Ok(()); } // Step 7 // https://fetch.spec.whatwg.org/#concept-header-list-set self.header_list.borrow_mut().set_raw(valid_name, vec![valid_value]); Ok(()) } } impl Headers { // https://fetch.spec.whatwg.org/#concept-headers-fill pub fn fill(&self,...
{ // Step 1 let value = normalize_value(value); // Step 2 let (mut valid_name, valid_value) = validate_name_and_value(name, value)?; valid_name = valid_name.to_lowercase(); // Step 3 if self.guard.get() == Guard::Immutable { return Err(Error::Type("Gua...
identifier_body
headers.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMe...
let value = header.value_string(); let name_value = (name, value); header_vec.push(name_value); } header_vec.sort(); header_vec } } impl Iterable for Headers { type Key = ByteString; type Value = ByteString; fn get_iterable_length(&self) -> u...
let borrowed_header_list = self.header_list.borrow(); let headers_iter = borrowed_header_list.iter(); let mut header_vec = vec![]; for header in headers_iter { let name = header.name().to_string();
random_line_split
color_dialog.rs
use winapi::shared::{minwindef::DWORD, windef::COLORREF}; use winapi::um::commdlg::{CHOOSECOLORW, CC_RGBINIT, ChooseColorW}; use winapi::um::wingdi::{GetBValue, GetRValue, GetGValue, RGB}; use crate::controls::ControlHandle; use crate::NwgError; use std::cell::{RefCell}; use std::{ptr, mem}; use std::pin::Pin; struct...
{ data: RefCell<InnerColorDialog>, } impl ColorDialog { pub fn builder() -> ColorDialogBuilder { ColorDialogBuilder { default_colors: Default::default() } } /** Execute the color dialog. This function will return `true` if the user select a color or `false` if the...
ColorDialog
identifier_name
color_dialog.rs
use winapi::shared::{minwindef::DWORD, windef::COLORREF}; use winapi::um::commdlg::{CHOOSECOLORW, CC_RGBINIT, ChooseColorW}; use winapi::um::wingdi::{GetBValue, GetRValue, GetGValue, RGB}; use crate::controls::ControlHandle; use crate::NwgError; use std::cell::{RefCell}; use std::{ptr, mem}; use std::pin::Pin; struct...
/** Execute the color dialog. This function will return `true` if the user select a color or `false` if the dialog is cancelled */ pub fn run<C: Into<ControlHandle>>(&self, owner: Option<C>) -> bool { if owner.is_some() { let ownder_handle = owner.unwrap().into(); s...
{ ColorDialogBuilder { default_colors: Default::default() } }
identifier_body
color_dialog.rs
use winapi::shared::{minwindef::DWORD, windef::COLORREF}; use winapi::um::commdlg::{CHOOSECOLORW, CC_RGBINIT, ChooseColorW}; use winapi::um::wingdi::{GetBValue, GetRValue, GetGValue, RGB}; use crate::controls::ControlHandle; use crate::NwgError; use std::cell::{RefCell}; use std::{ptr, mem}; use std::pin::Pin; struct...
let v = self.data.borrow().custom_colors[index]; [GetRValue(v), GetGValue(v), GetBValue(v)] } } /// The builder for a `ColorDialog` object. Use `ColorDialog::builder` to create one. pub struct ColorDialogBuilder { default_colors: [COLORREF; 16] } impl ColorDialogBuilder { pub fn saved_co...
if index > 15 { panic!("{:?} is outside the dialog saved color bounds", index); }
random_line_split
color_dialog.rs
use winapi::shared::{minwindef::DWORD, windef::COLORREF}; use winapi::um::commdlg::{CHOOSECOLORW, CC_RGBINIT, ChooseColorW}; use winapi::um::wingdi::{GetBValue, GetRValue, GetGValue, RGB}; use crate::controls::ControlHandle; use crate::NwgError; use std::cell::{RefCell}; use std::{ptr, mem}; use std::pin::Pin; struct...
self.data.borrow_mut().custom_colors[index] = RGB(color[0], color[1], color[2]); } /** Returns one of the saved color in the dialog. A dialog supports up to 16 colors (index: 0 to 15). Panics: - If the index is out of bound */ pub fn saved_color(&self, index: usize...
{ panic!("{:?} is outside the dialog saved color bounds", index); }
conditional_block
lib.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
// option. This file may not be copied, modified, or distributed // except according to those terms. #![crate_name = "rustc_borrowck"] #![unstable(feature = "rustc_private")] #![staged_api] #![crate_type = "dylib"] #![crate_type = "rlib"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2....
// 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
random_line_split
tick.rs
//use std::time::Duration; use mio::{EventLoop, Evented, EventLoopConfig, TryAccept}; use handler::LoopHandler; use internal::Message; use transport::Transport; use ::ProtocolFactory; pub struct Tick<T: TryAccept + Evented, F: ProtocolFactory<T::Output>> where <T as TryAccept>::Output: Transport { handler: Loop...
} impl<T: TryAccept + Evented, F: ProtocolFactory<T::Output>> Tick<T, F> where <T as TryAccept>::Output: Transport { pub fn new(protocol_factory: F) -> Tick<T, F> { Tick::configured(protocol_factory, TickConfig::new()) } pub fn configured(factory: F, config: TickConfig) -> Tick<T, F> { le...
{ TickConfig { transports_capacity: 8_192, notify_capacity: 8_192, } }
identifier_body
tick.rs
//use std::time::Duration; use mio::{EventLoop, Evented, EventLoopConfig, TryAccept}; use handler::LoopHandler; use internal::Message; use transport::Transport; use ::ProtocolFactory; pub struct Tick<T: TryAccept + Evented, F: ProtocolFactory<T::Output>> where <T as TryAccept>::Output: Transport { handler: Loop...
(&self) -> Notify { Notify { sender: self.event_loop.channel() } } pub fn accept(&mut self, listener: T) -> ::Result<::Id> { self.handler.listener(&mut self.event_loop, listener).map(::Id) } pub fn stream(&mut self, transport: T::Output) -> ::Result<::Id> { self.handler.stream(...
notify
identifier_name
tick.rs
//use std::time::Duration; use mio::{EventLoop, Evented, EventLoopConfig, TryAccept}; use handler::LoopHandler; use internal::Message; use transport::Transport; use ::ProtocolFactory; pub struct Tick<T: TryAccept + Evented, F: ProtocolFactory<T::Output>> where <T as TryAccept>::Output: Transport { handler: Loop...
sender: ::mio::Sender<Message> } impl Notify { /* pub fn timeout<F: FnOnce() + Send +'static>(&self, f: F, when: Duration) { let mut env = Some(f); let ms = when.as_secs() * 1_000 + (when.subsec_nanos() as u64) / 1_000_000; self.sender.send(Message::Timeout(Box::new(move || { ...
pub struct Notify {
random_line_split
linux.rs
#![allow(missing_docs)] use libc::{self, c_ulong, c_int}; use crate::{Result, NixPath}; use crate::errno::Errno; libc_bitflags!( pub struct MsFlags: c_ulong { /// Mount read-only MS_RDONLY; /// Ignore suid and sgid bits MS_NOSUID; /// Disallow access to device special files ...
<P, T, F>(p: Option<&P>, f: F) -> Result<T> where P:?Sized + NixPath, F: FnOnce(*const libc::c_char) -> T { match p { Some(path) => path.with_nix_path(|p_str| f(p_str.as_ptr())), None => Ok(f(std::ptr::null())) } } let res = with_opt_nix_path(so...
with_opt_nix_path
identifier_name
linux.rs
#![allow(missing_docs)] use libc::{self, c_ulong, c_int}; use crate::{Result, NixPath}; use crate::errno::Errno; libc_bitflags!( pub struct MsFlags: c_ulong { /// Mount read-only MS_RDONLY; /// Ignore suid and sgid bits MS_NOSUID; /// Disallow access to device special files ...
let res = with_opt_nix_path(source, |s| { target.with_nix_path(|t| { with_opt_nix_path(fstype, |ty| { with_opt_nix_path(data, |d| { unsafe { libc::mount( s, t.as_ptr(), ...
{ match p { Some(path) => path.with_nix_path(|p_str| f(p_str.as_ptr())), None => Ok(f(std::ptr::null())) } }
identifier_body
linux.rs
#![allow(missing_docs)] use libc::{self, c_ulong, c_int}; use crate::{Result, NixPath}; use crate::errno::Errno; libc_bitflags!( pub struct MsFlags: c_ulong { /// Mount read-only MS_RDONLY; /// Ignore suid and sgid bits MS_NOSUID; /// Disallow access to device special files ...
MS_SILENT; MS_POSIXACL; MS_UNBINDABLE; MS_PRIVATE; MS_SLAVE; MS_SHARED; MS_RELATIME; MS_KERNMOUNT; MS_I_VERSION; MS_STRICTATIME; MS_LAZYTIME; MS_ACTIVE; MS_NOUSER; MS_RMT_MASK; MS_MGC_VAL; MS_...
/// Linux 2.4.0 - Bind directory at different place MS_BIND; MS_MOVE; MS_REC;
random_line_split
config.rs
use uuid::Uuid; use std::str::FromStr; use std::fmt; use version; #[derive(Clone,Debug)] pub struct SessionConfig { pub user_agent: String, pub device_id: String, } impl Default for SessionConfig { fn default() -> SessionConfig { let device_id = Uuid::new_v4().hyphenated().to_string(); Se...
{ pub name: String, pub device_type: DeviceType, }
ConnectConfig
identifier_name
config.rs
use uuid::Uuid; use std::str::FromStr; use std::fmt; use version; #[derive(Clone,Debug)]
} impl Default for SessionConfig { fn default() -> SessionConfig { let device_id = Uuid::new_v4().hyphenated().to_string(); SessionConfig { user_agent: version::version_string(), device_id: device_id, } } } #[derive(Clone, Copy, Debug, Hash, PartialOrd, Ord, Pa...
pub struct SessionConfig { pub user_agent: String, pub device_id: String,
random_line_split
wrapper.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/. */ //! A safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, an...
} }
random_line_split
wrapper.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/. */ //! A safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, an...
(self) -> LayoutDataFlags { self.borrow_layout_data().as_ref().unwrap().flags } fn insert_flags(self, new_flags: LayoutDataFlags) { self.mutate_layout_data().unwrap().flags.insert(new_flags); } fn remove_flags(self, flags: LayoutDataFlags) { self.mutate_layout_data().unwrap...
flags
identifier_name
wrapper.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/. */ //! A safe wrapper for DOM nodes that prevents layout from mutating the DOM, from letting DOM nodes //! escape, an...
fn restyle_damage(self) -> RestyleDamage { // We need the underlying node to potentially access the parent in the // case of text nodes. This is safe as long as we don't let the parent // escape and never access its descendants. let mut node = unsafe { self.unsafe_get() }; ...
{ if self.get_pseudo_element_type().is_replaced_content() { let style = self.as_element().unwrap().resolved_style(); return match style.as_ref().get_counters().content { content::T::Items(ref value) if !value.is_empty() => { TextContent::GeneratedCont...
identifier_body
failed-doctest-output.rs
// Issue #51162: A failed doctest was not printing its stdout/stderr // FIXME: if/when the output of the test harness can be tested on its own, this test should be
// compile-flags:--test --test-args --test-threads=1 // rustc-env:RUST_BACKTRACE=0 // normalize-stdout-test: "src/test/rustdoc-ui" -> "$$DIR" // normalize-stdout-test "finished in \d+\.\d+s" -> "finished in $$TIME" // failure-status: 101 // doctest fails at runtime /// ``` /// println!("stdout 1"); /// eprintln!("std...
// adapted to use that, and that normalize line can go away
random_line_split
failed-doctest-output.rs
// Issue #51162: A failed doctest was not printing its stdout/stderr // FIXME: if/when the output of the test harness can be tested on its own, this test should be // adapted to use that, and that normalize line can go away // compile-flags:--test --test-args --test-threads=1 // rustc-env:RUST_BACKTRACE=0 // normalize...
; // doctest fails at compile time /// ``` /// no /// ``` pub struct OtherStruct;
SomeStruct
identifier_name
timer_timerfd.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ pub it_interval: timespec, pub it_value: timespec, } extern { pub fn timerfd_create(clockid: libc::c_int, flags: libc::c_int) -> libc::c_int; pub fn timerfd_settime(fd: libc::c_int, flags: libc::c_int, ...
itimerspec
identifier_name
timer_timerfd.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
let fd = event.data as libc::c_int; if fd == input { let mut buf = [0,..1]; // drain the input file descriptor of its input let _ = FileDesc::new(fd, false).inner_read(buf).unwrap(); incoming = true; } else { ...
let mut incoming = false; for event in events.slice_to(n as uint).iter() {
random_line_split
timer_timerfd.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} } while incoming { match messages.try_recv() { Data(NewTimer(fd, chan, one, timeval)) => { // acknowledge we have the new channel, we will never send // another message to the old channel chan.send(()...
{ drop(list.remove(i)); del(efd, fd); }
conditional_block
timer_timerfd.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn del(efd: libc::c_int, fd: libc::c_int) { let event = imp::epoll_event { events: 0, data: 0 }; let ret = unsafe { imp::epoll_ctl(efd, imp::EPOLL_CTL_DEL, fd, &event) }; assert_eq!(ret, 0); } add(efd, input); let events: [imp::epoll_event,..16] = unsafe { m...
{ let event = imp::epoll_event { events: imp::EPOLLIN as u32, data: fd as i64, }; let ret = unsafe { imp::epoll_ctl(efd, imp::EPOLL_CTL_ADD, fd, &event) }; assert_eq!(ret, 0); }
identifier_body
store.rs
/* * Created on Tue Oct 19 2021 * * Copyright (c) storycraft. Licensed under the MIT Licence. */ use std::sync::Arc; use font_kit::{ canvas::{Canvas, Format, RasterizationOptions}, hinting::HintingOptions, }; use pathfinder_geometry::transform2d::Transform2F; use rect_packer::DensePacker; use rustc_hash::...
{ pub raster_rect: Rect<i32, PixelUnit>, pub bitmap: Canvas, }
GlyphRasterData
identifier_name
store.rs
/* * Created on Tue Oct 19 2021 * * Copyright (c) storycraft. Licensed under the MIT Licence. */ use std::sync::Arc; use font_kit::{ canvas::{Canvas, Format, RasterizationOptions}, hinting::HintingOptions, }; use pathfinder_geometry::transform2d::Transform2F; use rect_packer::DensePacker; use rustc_hash::...
else { let glyph_data = self.raster_glyph(glyph_id)?; let pixel_rect = { let packer_rect = self.packer.pack( glyph_data.bitmap.size.x(), glyph_data.bitmap.size.y(), false, )?; Rect { ...
{ Some(*info) }
conditional_block
store.rs
/* * Created on Tue Oct 19 2021
use std::sync::Arc; use font_kit::{ canvas::{Canvas, Format, RasterizationOptions}, hinting::HintingOptions, }; use pathfinder_geometry::transform2d::Transform2F; use rect_packer::DensePacker; use rustc_hash::FxHashMap; use storyboard_graphics::{ math::Rect, texture::{resources::TextureResources, Text...
* * Copyright (c) storycraft. Licensed under the MIT Licence. */
random_line_split
helper_thread.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(fd: libc::c_int) { FileDesc::new(fd, false).inner_write([0]).ok().unwrap(); } pub fn close(fd: libc::c_int) { let _fd = FileDesc::new(fd, true); } } #[cfg(windows)] mod imp { use libc::{BOOL, LPCSTR, HANDLE, LPSECURITY_ATTRIBUTES, CloseHandle}; use std::ptr; use libc; pub...
signal
identifier_name
helper_thread.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} } /// Sends a message to a spawned worker thread. /// /// This is only valid if the worker thread has previously booted pub fn send(&'static self, msg: M) { unsafe { let _guard = self.lock.lock(); // Must send and *then* signal to ensure that the child re...
{ let (tx, rx) = channel(); *self.chan.get() = mem::transmute(box tx); let (receive, send) = imp::new(); *self.signal.get() = send as uint; let t = f(); task::spawn(proc() { bookkeeping::decrement(); ...
conditional_block
helper_thread.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
value: 0 as *mut Sender<$m>, marker1: ::std::kinds::marker::InvariantType, }, signal: ::std::ty::Unsafe { value: 0, marker1: ::std::kinds::marker::InvariantType, }, initialized: ::std::ty::Unsafe { value: false, mark...
lock: ::std::rt::mutex::NATIVE_MUTEX_INIT, chan: ::std::ty::Unsafe {
random_line_split
compiler_plugin.rs
use std::io::stdin; use std::io::stdout; use std::str;
pub struct GenRequest<'a> { pub file_descriptors: &'a [FileDescriptorProto], pub files_to_generate: &'a [ProtoPathBuf], pub parameter: &'a str, } pub struct GenResult { pub name: String, pub content: Vec<u8>, } pub fn plugin_main<F>(gen: F) -> anyhow::Result<()> where F: Fn(&GenRequest) -> an...
use protobuf::descriptor::FileDescriptorProto; use protobuf::plugin::*; use protobuf::Message; use protobuf_parse::ProtoPathBuf;
random_line_split
compiler_plugin.rs
use std::io::stdin; use std::io::stdout; use std::str; use protobuf::descriptor::FileDescriptorProto; use protobuf::plugin::*; use protobuf::Message; use protobuf_parse::ProtoPathBuf; pub struct GenRequest<'a> { pub file_descriptors: &'a [FileDescriptorProto], pub files_to_generate: &'a [ProtoPathBuf], pu...
<F>(gen: F) -> anyhow::Result<()> where F: Fn(&GenRequest) -> anyhow::Result<Vec<GenResult>>, { let req = CodeGeneratorRequest::parse_from_reader(&mut stdin()).unwrap(); let result = gen(&GenRequest { file_descriptors: &req.proto_file, files_to_generate: &req .file_to_generate ...
plugin_main
identifier_name
main.rs
extern crate git2; extern crate chrono; #[macro_use] extern crate serde_derive; extern crate docopt; extern crate core; extern crate regex; #[macro_use] extern crate prettytable; #[cfg(test)] extern crate tempdir;
use docopt::Docopt; mod snapshot; mod heatmap; mod mailmap; mod personal; #[cfg(test)] mod test; #[derive(Debug, Deserialize)] pub struct Args { arg_path: String } #[cfg(not(test))] fn main() { const USAGE: &'static str = " usage: gitostat [options] <path> Options: -h, --help show this message "; let ar...
random_line_split
main.rs
extern crate git2; extern crate chrono; #[macro_use] extern crate serde_derive; extern crate docopt; extern crate core; extern crate regex; #[macro_use] extern crate prettytable; #[cfg(test)] extern crate tempdir; use docopt::Docopt; mod snapshot; mod heatmap; mod mailmap; mod personal; #[cfg(test)] mod test; #[deri...
() { const USAGE: &'static str = " usage: gitostat [options] <path> Options: -h, --help show this message "; let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); match gitostat::run(&args) { Ok(()) => {}, Err(e) => println!("error: ...
main
identifier_name
main.rs
extern crate git2; extern crate chrono; #[macro_use] extern crate serde_derive; extern crate docopt; extern crate core; extern crate regex; #[macro_use] extern crate prettytable; #[cfg(test)] extern crate tempdir; use docopt::Docopt; mod snapshot; mod heatmap; mod mailmap; mod personal; #[cfg(test)] mod test; #[deri...
let mut vec: Vec<usize> = num_files.values().cloned().collect(); vec.sort_by(|a, b| b.cmp(a)); let max = cmp::max(1, vec[0]); const WIDTH: usize = 60; let coeff = if max > WIDTH { WIDTH as f32 / max as f32 } else { 1f32 }; prin...
{ // skip binary files because they don't counted in diffs let files = repo.snapshot(commit, true)?; authors.blame(&files, mailmap)?; println!("Scaned {}", files.len()); }
conditional_block
main.rs
extern crate git2; extern crate chrono; #[macro_use] extern crate serde_derive; extern crate docopt; extern crate core; extern crate regex; #[macro_use] extern crate prettytable; #[cfg(test)] extern crate tempdir; use docopt::Docopt; mod snapshot; mod heatmap; mod mailmap; mod personal; #[cfg(test)] mod test; #[deri...
print!("[{}/{}]\r", i+1, commits.len()); heatmap.append(&commit.author().when()); authors.append(&commit, mailmap)?; let files = repo.snapshot(&commit, false)?; let key = format!("{}", files.datetime.format("%Y-%W")); let number = num_files.entry...
{ let mut revwalk = repo.revwalk()?; revwalk.push_head()?; revwalk.set_sorting(git2::SORT_TOPOLOGICAL); let commits: Vec<git2::Commit> = revwalk.filter_map(|oid| { // trying lookup commit in repo, skip if any error let commit = otry!(repo.find_commit(otry!(oid)))...
identifier_body
winit.rs
use std::{cell::RefCell, rc::Rc, sync::atomic::Ordering, time::Duration}; #[cfg(feature = "debug")] use smithay::backend::renderer::gles2::Gles2Texture; #[cfg(feature = "egl")] use smithay::{ backend::renderer::{ImportDma, ImportEgl}, wayland::dmabuf::init_dmabuf_global, }; use smithay::{ backend::{ ...
(log: Logger) { let mut event_loop = EventLoop::try_new().unwrap(); let display = Rc::new(RefCell::new(Display::new())); let (backend, mut winit) = match winit::init(log.clone()) { Ok(ret) => ret, Err(err) => { slog::crit!(log, "Failed to initialize Winit backend: {}", err); ...
run_winit
identifier_name
winit.rs
use std::{cell::RefCell, rc::Rc, sync::atomic::Ordering, time::Duration}; #[cfg(feature = "debug")] use smithay::backend::renderer::gles2::Gles2Texture; #[cfg(feature = "egl")] use smithay::{ backend::renderer::{ImportDma, ImportEgl}, wayland::dmabuf::init_dmabuf_global, }; use smithay::{ backend::{ ...
state::{AnvilState, Backend}, }; pub const OUTPUT_NAME: &str = "winit"; pub struct WinitData { #[cfg(feature = "debug")] fps_texture: Gles2Texture, #[cfg(feature = "debug")] pub fps: fps_ticker::Fps, full_redraw: u8, } impl Backend for WinitData { fn seat_name(&self) -> String { S...
use crate::{ drawing::*,
random_line_split
winit.rs
use std::{cell::RefCell, rc::Rc, sync::atomic::Ordering, time::Duration}; #[cfg(feature = "debug")] use smithay::backend::renderer::gles2::Gles2Texture; #[cfg(feature = "egl")] use smithay::{ backend::renderer::{ImportDma, ImportEgl}, wayland::dmabuf::init_dmabuf_global, }; use smithay::{ backend::{ ...
fn reset_buffers(&mut self, _output: &Output) { self.full_redraw = 4; } } pub fn run_winit(log: Logger) { let mut event_loop = EventLoop::try_new().unwrap(); let display = Rc::new(RefCell::new(Display::new())); let (backend, mut winit) = match winit::init(log.clone()) { Ok(ret) =>...
{ String::from("winit") }
identifier_body
error.rs
use std::error::Error as StdError; use std::convert::From; use std::fmt; use diesel::result::Error as DieselError; use rocket::http::Status; use rocket::response::{Response, Responder}; #[derive(Debug)] pub enum Error { NotFound, InternalServerError, } impl fmt::Display for Error { fn fmt(&self, f: &mut f...
_ => Err(Status::InternalServerError), } } }
Error::NotFound => Err(Status::NotFound),
random_line_split
error.rs
use std::error::Error as StdError; use std::convert::From; use std::fmt; use diesel::result::Error as DieselError; use rocket::http::Status; use rocket::response::{Response, Responder}; #[derive(Debug)] pub enum Error { NotFound, InternalServerError, } impl fmt::Display for Error { fn fmt(&self, f: &mut f...
(&self) -> &str { match *self { Error::NotFound => "Record not found", Error::InternalServerError => "Internal server error", } } } impl<'r> Responder<'r> for Error { fn respond(self) -> Result<Response<'r>, Status> { match self { Error::NotFound => ...
description
identifier_name
static-function-pointer.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(x: int) -> int { 2 * x } static F: fn(int) -> int = f; static mut G: fn(int) -> int = f; pub fn main() { assert_eq!(F(42), 42); unsafe { assert_eq!(G(42), 42); G = g; assert_eq!(G(42), 84); } }
g
identifier_name
static-function-pointer.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
static F: fn(int) -> int = f; static mut G: fn(int) -> int = f; pub fn main() { assert_eq!(F(42), 42); unsafe { assert_eq!(G(42), 42); G = g; assert_eq!(G(42), 84); } }
{ 2 * x }
identifier_body
lib.rs
#![crate_name="redox"] #![crate_type="rlib"] #![feature(alloc)] #![feature(asm)] #![feature(box_syntax)]
#![feature(lang_items)] #![feature(no_std)] #![no_std] extern crate alloc; pub use alloc::boxed::*; pub use audio::wav::*; pub use common::event::*; pub use common::queue::*; pub use common::random::*; pub use common::string::*; pub use common::time::*; pub use common::vec::*; pub use graphics::bmp::*; pub use gra...
#![feature(core_simd)] #![feature(core_slice_ext)] #![feature(core_str_ext)]
random_line_split
camera_subscriber.rs
// Example that requires a lot of processing power to handle all the data received. use std::sync::Mutex; use std::time::Instant; fn main() {
// Initialize node rosrust::init("listener"); let now = Mutex::new(Instant::now()); // Create subscriber // The subscriber is stopped when the returned object is destroyed let _subscriber_raii = rosrust::subscribe( "/usb_cam/image_raw", 1, move |v: rosrust_msg::sensor_...
env_logger::init();
random_line_split
camera_subscriber.rs
// Example that requires a lot of processing power to handle all the data received. use std::sync::Mutex; use std::time::Instant; fn main()
duration.as_secs() * 1000 + u64::from(duration.subsec_millis()), v.data.len(), v.header.stamp, ); }, ) .unwrap(); // Block the thread until a shutdown signal is received rosrust::spin(); }
{ env_logger::init(); // Initialize node rosrust::init("listener"); let now = Mutex::new(Instant::now()); // Create subscriber // The subscriber is stopped when the returned object is destroyed let _subscriber_raii = rosrust::subscribe( "/usb_cam/image_raw", 1, mov...
identifier_body
camera_subscriber.rs
// Example that requires a lot of processing power to handle all the data received. use std::sync::Mutex; use std::time::Instant; fn
() { env_logger::init(); // Initialize node rosrust::init("listener"); let now = Mutex::new(Instant::now()); // Create subscriber // The subscriber is stopped when the returned object is destroyed let _subscriber_raii = rosrust::subscribe( "/usb_cam/image_raw", 1, ...
main
identifier_name
main.rs
extern crate getopts; extern crate regex; use std::os; fn main() { let args = os::args(); let program = args[0].clone(); let opt_matches = match getopts::getopts(args.tail(), options().as_slice()) { Ok(m) =>
Err(f) => { println!("{}\n", f.to_string()); print_usage(program.as_slice()); return; } }; if opt_matches.opt_present("h") { print_usage(program.as_slice()); return; } } struct CmdContext { cmd_args: Vec<String>, in_delim: Vec...
{ m }
conditional_block
main.rs
extern crate getopts; extern crate regex; use std::os; fn main() { let args = os::args(); let program = args[0].clone(); let opt_matches = match getopts::getopts(args.tail(), options().as_slice()) { Ok(m) => { m } Err(f) => { println!("{}\n", f.to_string()); print_...
let opts = options(); let commands = "Commands: shape Get the shape of this matrix reshape <new_shape> Reshape this matrix into a new one map <cmd> Map a command on each selected cell agg <axes> <cmd> Aggregate a matrix along the specified axes ...
fn print_usage(program: &str) {
random_line_split
main.rs
extern crate getopts; extern crate regex; use std::os; fn main() { let args = os::args(); let program = args[0].clone(); let opt_matches = match getopts::getopts(args.tail(), options().as_slice()) { Ok(m) => { m } Err(f) => { println!("{}\n", f.to_string()); print_...
{ cmd_args: Vec<String>, in_delim: Vec<regex::Regex>, out_delim: Vec<regex::Regex>, nprocs: u32, empty: String, } fn shape(args: Vec<String>) { } fn reshape(args: Vec<String>) { } fn map(args: Vec<String>) { } fn agg(args: Vec<String>) { } fn options() -> Vec<getopts::OptGroup> ...
CmdContext
identifier_name
handles.rs
//! Handles wrapping Rust models use pact_matching::models::{RequestResponsePact, Consumer, Provider, RequestResponseInteraction}; use lazy_static::*; use maplit::*; use std::sync::Mutex; use std::cell::RefCell; use std::collections::HashMap; lazy_static! { static ref PACT_HANDLES: Mutex<HashMap<usize, RefCell<Requ...
<R>(&self, f: &dyn Fn(usize, &mut RequestResponseInteraction) -> R) -> Option<R> { let mut handles = PACT_HANDLES.lock().unwrap(); handles.get_mut(&self.pact).map(|inner| { match inner.borrow_mut().interactions.get_mut(self.interaction - 1) { Some(inner_i) => Some(f(self.interaction - 1, inner_i))...
with_interaction
identifier_name
handles.rs
//! Handles wrapping Rust models use pact_matching::models::{RequestResponsePact, Consumer, Provider, RequestResponseInteraction}; use lazy_static::*; use maplit::*; use std::sync::Mutex; use std::cell::RefCell; use std::collections::HashMap; lazy_static! { static ref PACT_HANDLES: Mutex<HashMap<usize, RefCell<Requ...
#[repr(C)] #[derive(Debug, Clone)] /// Request or Response enum pub enum InteractionPart { /// Request part Request, /// Response part Response } impl PactHandle { /// Creates a new handle to a Pact model pub fn new(consumer: &str, provider: &str) -> Self { let mut handles = PACT_HANDLES.lock().unwrap...
pub interaction: usize }
random_line_split
handles.rs
//! Handles wrapping Rust models use pact_matching::models::{RequestResponsePact, Consumer, Provider, RequestResponseInteraction}; use lazy_static::*; use maplit::*; use std::sync::Mutex; use std::cell::RefCell; use std::collections::HashMap; lazy_static! { static ref PACT_HANDLES: Mutex<HashMap<usize, RefCell<Requ...
/// Invokes the closure with the inner Pact model pub fn with_pact<R>(&self, f: &dyn Fn(usize, &mut RequestResponsePact) -> R) -> Option<R> { let mut handles = PACT_HANDLES.lock().unwrap(); handles.get_mut(&self.pact).map(|inner| f(self.pact - 1, &mut inner.borrow_mut())) } } impl InteractionHandle { ...
{ let mut handles = PACT_HANDLES.lock().unwrap(); let id = handles.len() + 1; handles.insert(id, RefCell::new(RequestResponsePact { consumer: Consumer { name: consumer.to_string() }, provider: Provider { name: provider.to_string() }, .. RequestResponsePact::default() })); PactHandl...
identifier_body
nonzero.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
unsafe impl Zeroable for i16 {} unsafe impl Zeroable for u16 {} unsafe impl Zeroable for i32 {} unsafe impl Zeroable for u32 {} unsafe impl Zeroable for i64 {} unsafe impl Zeroable for u64 {} /// A wrapper type for raw pointers and integers that will never be /// NULL or 0 that might allow certain optimizations. #[lan...
unsafe impl<T:?Sized> Zeroable for *mut T {} unsafe impl Zeroable for isize {} unsafe impl Zeroable for usize {} unsafe impl Zeroable for i8 {} unsafe impl Zeroable for u8 {}
random_line_split
nonzero.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(inner: T) -> NonZero<T> { NonZero(inner) } } impl<T: Zeroable> Deref for NonZero<T> { type Target = T; #[inline] fn deref<'a>(&'a self) -> &'a T { let NonZero(ref inner) = *self; inner } } #[cfg(not(stage0))] impl<T: Zeroable+CoerceUnsized<U>, U: Zeroable> CoerceUnsized<N...
new
identifier_name
nonzero.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} #[cfg(not(stage0))] impl<T: Zeroable+CoerceUnsized<U>, U: Zeroable> CoerceUnsized<NonZero<U>> for NonZero<T> {}
{ let NonZero(ref inner) = *self; inner }
identifier_body
btreemap.rs
use criterion::{black_box, AxisScale, BenchmarkId, Criterion, PlotConfiguration}; use rand::prelude::*; use std::collections::BTreeMap; const STEPS: [usize; 6] = [1, 10, 100, 1000, 10_000, 100_000]; pub fn insert(c: &mut Criterion) {
let mut rng = StdRng::seed_from_u64(0x1234abcd); let mut sl: BTreeMap<usize, usize> = std::iter::repeat_with(|| rng.gen()).take(i).collect(); b.iter(|| { sl.insert(rng.gen(), rng.gen()); }) }); } } pub fn rand_access(c: &mut C...
let mut group = c.benchmark_group("BTreeMap Insert"); group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)); for i in STEPS { group.bench_function(BenchmarkId::from_parameter(i), |b| {
random_line_split
btreemap.rs
use criterion::{black_box, AxisScale, BenchmarkId, Criterion, PlotConfiguration}; use rand::prelude::*; use std::collections::BTreeMap; const STEPS: [usize; 6] = [1, 10, 100, 1000, 10_000, 100_000]; pub fn insert(c: &mut Criterion) { let mut group = c.benchmark_group("BTreeMap Insert"); group.plot_config(Plot...
{ c.bench_function("BTreeMap Iter", |b| { let mut rng = StdRng::seed_from_u64(0x1234abcd); let sl: BTreeMap<usize, usize> = std::iter::repeat_with(|| rng.gen()).take(100_000).collect(); b.iter(|| { for el in &sl { black_box(el); } ...
identifier_body
btreemap.rs
use criterion::{black_box, AxisScale, BenchmarkId, Criterion, PlotConfiguration}; use rand::prelude::*; use std::collections::BTreeMap; const STEPS: [usize; 6] = [1, 10, 100, 1000, 10_000, 100_000]; pub fn
(c: &mut Criterion) { let mut group = c.benchmark_group("BTreeMap Insert"); group.plot_config(PlotConfiguration::default().summary_scale(AxisScale::Logarithmic)); for i in STEPS { group.bench_function(BenchmarkId::from_parameter(i), |b| { let mut rng = StdRng::seed_from_u64(0x1234abcd);...
insert
identifier_name
interop.rs
use std::os::raw::c_char; use std; use util; use d3dx; use shared_dx9::util::write_log_file; use global_state::HookState; use types::interop::*; lazy_static! { pub static ref LOG_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(()); } unsafe fn loggit(prefix: &str, category: *const c_char, message: *const c_...
Err(e) => { write_log_file(&format!("Unexpected conf error value: {:?}", e)); return on_init_error_code; } }; // get module path (exe that has loaded this dll). let exemodule = match util::get_module_name() { Err(e) => { write_log_file(&format!( ...
{ write_log_file(&format!("Unexpected conf return: {:?} {:?}", a, b)); return on_init_error_code; }
conditional_block
interop.rs
use std::os::raw::c_char; use std; use util; use d3dx; use shared_dx9::util::write_log_file; use global_state::HookState; use types::interop::*; lazy_static! { pub static ref LOG_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(()); } unsafe fn
(prefix: &str, category: *const c_char, message: *const c_char) -> () { use std::ffi::CStr; let _lock = LOG_MUTEX.lock(); // convert the c_strs to rust strs; if it works, we get a &str. If it doesn't, // we get an error. format error to make a String, store that in a mutable to prevent drop, // a...
loggit
identifier_name