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
idt.rs
use x86_64::PrivilegeLevel::{self, Ring0}; use x86_64::VirtAddr; // These constants MUST have defined with same values as those in src/asm_routines/constants.asm // They also MUST match the ones in plan.md // If a constant defined here doesn't exists in that file, then it's also fine const GDT_SELECTOR_CODE: u16 = 0x0...
; assert!(ist_offset < 0b1000); assert!(present || (pointer == 0 && ring == Ring0)); // pointer and ring must be 0 if not present // example options: present => 1, ring 0 => 00, interrupt gate => 0, interrupt gate => 1110 let options: u8 = 0b0_00_0_1110 | ((ring as u8) << 5) ...
{ 0 }
conditional_block
idt.rs
use x86_64::VirtAddr; // These constants MUST have defined with same values as those in src/asm_routines/constants.asm // They also MUST match the ones in plan.md // If a constant defined here doesn't exists in that file, then it's also fine const GDT_SELECTOR_CODE: u16 = 0x08; pub const ADDRESS: usize = 0; pub const ...
use x86_64::PrivilegeLevel::{self, Ring0};
random_line_split
idt.rs
use x86_64::PrivilegeLevel::{self, Ring0}; use x86_64::VirtAddr; // These constants MUST have defined with same values as those in src/asm_routines/constants.asm // They also MUST match the ones in plan.md // If a constant defined here doesn't exists in that file, then it's also fine const GDT_SELECTOR_CODE: u16 = 0x0...
( present: bool, pointer: u64, ring: PrivilegeLevel, ist_index: Option<u8>, ) -> Descriptor { let ist_offset = if let Some(i) = ist_index { i + 1 } else { 0 }; assert!(ist_offset < 0b1000); assert!(present || (pointer == 0 && ring == Ring0)); // pointer and ring must be 0 if not pres...
new
identifier_name
idt.rs
use x86_64::PrivilegeLevel::{self, Ring0}; use x86_64::VirtAddr; // These constants MUST have defined with same values as those in src/asm_routines/constants.asm // They also MUST match the ones in plan.md // If a constant defined here doesn't exists in that file, then it's also fine const GDT_SELECTOR_CODE: u16 = 0x0...
}
{ let ist_offset = if let Some(i) = ist_index { i + 1 } else { 0 }; assert!(ist_offset < 0b1000); assert!(present || (pointer == 0 && ring == Ring0)); // pointer and ring must be 0 if not present // example options: present => 1, ring 0 => 00, interrupt gate => 0, interrupt gate => 1110 ...
identifier_body
from_form_value.rs
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6, SocketAddr}; use std::str::FromStr; use http::RawStr; /// Trait to create instance of some type from a form value; expected from field /// types in structs deriving `FromForm`. /// /// When deriving the `FromForm` trait, Rocket uses the `FromFormV...
}
{ match T::from_form_value(v) { ok@Ok(_) => Ok(ok), e@Err(_) => Ok(e), } }
identifier_body
from_form_value.rs
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6, SocketAddr}; use std::str::FromStr; use http::RawStr; /// Trait to create instance of some type from a form value; expected from field /// types in structs deriving `FromForm`. /// /// When deriving the `FromForm` trait, Rocket uses the `FromFormV...
/// The `FromForm` implementation generated by Rocket will call /// `String::from_form_value` for the `name` field, and `u16::from_form_value` /// for the `age` field. The `Person` structure can only be created from a form /// if both calls return successfully. /// /// ## Catching Validation Errors /// /// Sometimes yo...
/// ``` ///
random_line_split
from_form_value.rs
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6, SocketAddr}; use std::str::FromStr; use http::RawStr; /// Trait to create instance of some type from a form value; expected from field /// types in structs deriving `FromForm`. /// /// When deriving the `FromForm` trait, Rocket uses the `FromFormV...
() -> Option<Self> { None } } impl<'v> FromFormValue<'v> for &'v RawStr { type Error =!; // This just gives the raw string. #[inline(always)] fn from_form_value(v: &'v RawStr) -> Result<Self, Self::Error> { Ok(v) } } impl<'v> FromFormValue<'v> for String { type Error = &'v...
default
identifier_name
issue-32922.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ foo! {}; bar! {}; let mut a = true; baz!(a); }
identifier_body
issue-32922.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#![allow(warnings)] macro_rules! foo { () => { let x = 1; macro_rules! bar { () => {x} } let _ = bar!(); }} macro_rules! m { // test issue #31856 ($n:ident) => ( let a = 1; let $n = a; ) } macro_rules! baz { ($i:ident) => { let mut $i = 2; $i = $i + 1; } } ...
// compile-pass // skip-codegen
random_line_split
issue-32922.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { foo! {}; bar! {}; let mut a = true; baz!(a); }
main
identifier_name
compositor_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Communication with the compositor thread. use crate::compositor::CompositingReason; use crate::SendableFrame...
} impl Clone for CompositorProxy { fn clone(&self) -> CompositorProxy { CompositorProxy { sender: self.sender.clone(), event_loop_waker: self.event_loop_waker.clone(), } } } /// The port that the compositor receives messages on. pub struct CompositorReceiver { pub ...
{ if let Err(err) = self.sender.send(msg) { warn!("Failed to send response ({:?}).", err); } self.event_loop_waker.wake(); }
identifier_body
compositor_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Communication with the compositor thread. use crate::compositor::CompositingReason; use crate::SendableFrame...
{ /// A channel to the compositor. pub sender: CompositorProxy, /// A port on which messages inbound to the compositor can be received. pub receiver: CompositorReceiver, /// A channel to the constellation. pub constellation_chan: Sender<ConstellationMsg>, /// A channel to the time profiler ...
InitialCompositorState
identifier_name
compositor_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Communication with the compositor thread. use crate::compositor::CompositingReason; use crate::SendableFrame...
/// Get screen size. GetScreenSize(IpcSender<DeviceIntSize>), /// Get screen available size. GetScreenAvailSize(IpcSender<DeviceIntSize>), } impl Debug for Msg { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { match *self { Msg::ShutdownComplete => write!(f, "ShutdownCom...
/// Get Window Informations size and position. GetClientWindow(IpcSender<(DeviceIntSize, DeviceIntPoint)>),
random_line_split
negative_log_likelihood.rs
//! TODO: DOC //! use capnp_util::*; use co::{IBackend, ITensorDesc, SharedTensor}; use layer::*; use juice_capnp::negative_log_likelihood_config as capnp_config; use util::{ArcLock, native_backend}; #[derive(Debug, Clone)] #[allow(missing_copy_implementations)] /// NegativeLogLikelihood Loss Layer pub struct Negativ...
(reader: Self::Reader) -> Self { let num_classes = reader.get_num_classes() as usize; NegativeLogLikelihoodConfig { num_classes: num_classes } } } impl Into<LayerType> for NegativeLogLikelihoodConfig { fn into(self) -> LayerType { LayerType::NegativeLogLikelihood(self) } }
read_capnp
identifier_name
negative_log_likelihood.rs
//! TODO: DOC //! use capnp_util::*; use co::{IBackend, ITensorDesc, SharedTensor}; use layer::*; use juice_capnp::negative_log_likelihood_config as capnp_config; use util::{ArcLock, native_backend}; #[derive(Debug, Clone)] #[allow(missing_copy_implementations)] /// NegativeLogLikelihood Loss Layer pub struct Negativ...
} impl<B: IBackend> ILayer<B> for NegativeLogLikelihood { impl_ilayer_loss!(); fn sync_native(&self) -> bool { true } fn reshape(&mut self, backend: ::std::rc::Rc<B>, input_data: &mut Vec<ArcLock<SharedTensor<f32>>>, input_gradient: &mut Vec<ArcLo...
{ match input_shape.len() { 1 => 1, 2 => input_shape[0], _ => panic!("NegativeLogLikelihood layer only supports 1D/2D inputs"), } }
identifier_body
negative_log_likelihood.rs
//! TODO: DOC //! use capnp_util::*; use co::{IBackend, ITensorDesc, SharedTensor}; use layer::*; use juice_capnp::negative_log_likelihood_config as capnp_config; use util::{ArcLock, native_backend}; #[derive(Debug, Clone)] #[allow(missing_copy_implementations)] /// NegativeLogLikelihood Loss Layer pub struct Negativ...
.as_slice::<f32>(); let mut writable_loss = Vec::<f32>::new(); for &label_value in native_labels { let probability_value = native_probabilities[label_value as usize]; writable_loss.push(-probability_value); } let mut loss = writable_loss.iter().fold(0...
let native_probabilities = probabilities.read(native.device()).unwrap()
random_line_split
utf8_idents.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 ...
10; let غداء = 10; let լանչ = 10; let обед = 10; let абед = 10; let μεσημεριανό = 10; let hádegismatur = 10; let ручек = 10; let ăn_trưa = 10; let อาหารกลางวัน = 10; // Lunchy arithmetic, mm. assert_eq!(hádegismatur * ручек * обед, 1000); assert_eq!(10, ארוחת_צהריי); ...
nguages. let ランチ = 10; let 午餐 = 10; let ארוחת_צהריי =
identifier_name
utf8_idents.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 ...
pub fn main() { let ε = 0.00001; let Π = 3.14; let लंच = Π * Π + 1.54; assert!(num::abs((लंच - 1.54) - (Π * Π)) < ε); assert_eq!(საჭმელად_გემრიელი_სადილი(), 0); } fn საჭმელად_გემრიელი_სადილი() -> int { // Lunch in several languages. let ランチ = 10; let 午餐 = 10; let ארוחת_צהריי = 1...
use std::num;
random_line_split
utf8_idents.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 ...
t غداء = 10; let լանչ = 10; let обед = 10; let абед = 10; let μεσημεριανό = 10; let hádegismatur = 10; let ручек = 10; let ăn_trưa = 10; let อาหารกลางวัน = 10; // Lunchy arithmetic, mm. assert_eq!(hádegismatur * ручек * обед, 1000); assert_eq!(10, ארוחת_צהריי); assert_...
identifier_body
htmltableelement.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::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableElementBinding; use dom::bindings...
// https://html.spec.whatwg.org/multipage/#dom-table-deletecaption fn DeleteCaption(&self) { if let Some(caption) = self.GetCaption() { NodeCast::from_ref(caption.r()).remove_self(); } } // https://html.spec.whatwg.org/multipage/#dom-table-createtbody fn CreateTBody(&s...
{ let caption = match self.GetCaption() { Some(caption) => caption, None => { let caption = HTMLTableCaptionElement::new("caption".to_owned(), None, docum...
identifier_body
htmltableelement.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::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableElementBinding; use dom::bindings...
} impl HTMLTableElement { pub fn get_background_color(&self) -> Option<RGBA> { self.background_color.get() } pub fn get_border(&self) -> Option<u32> { self.border.get() } pub fn get_cellspacing(&self) -> Option<u32> { self.cellspacing.get() } pub fn get_width(&se...
assert!(node.InsertBefore(NodeCast::from_ref(tbody.r()), reference_element.r()).is_ok()); tbody }
random_line_split
htmltableelement.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::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableElementBinding; use dom::bindings...
_ => {}, } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue { match local_name { &atom!("border") => AttrValue::from_u32(value, 1), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } }...
let width = mutation.new_value(attr).map(|value| { str::parse_length(&value) }); self.width.set(width.unwrap_or(LengthOrPercentageOrAuto::Auto)); },
conditional_block
htmltableelement.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::attr::{Attr, AttrValue}; use dom::bindings::codegen::Bindings::HTMLTableElementBinding; use dom::bindings...
(&self, new_caption: Option<&HTMLTableCaptionElement>) { let node = NodeCast::from_ref(self); if let Some(ref caption) = self.GetCaption() { NodeCast::from_ref(caption.r()).remove_self(); } if let Some(caption) = new_caption { assert!(node.InsertBefore(NodeCast:...
SetCaption
identifier_name
nats_message_stream.rs
use crate::event::{Error, EventStreamConfig, Result}; use futures::{channel::{mpsc as futures_mpsc, mpsc::UnboundedSender}, stream::StreamExt}; use rants::{error::Error as RantsError, native_tls::TlsConnector, Client, ...
let tls_connector = tls_connector.build()?; client.set_tls_connector(tls_connector).await; // Connect to the server. If a timeout was set, we want to ensure we establish a connection // before exiting the function. If we do not connect within the timeout we return an error. // ...
{ tls_connector.add_root_certificate(certificate.into()); }
conditional_block
nats_message_stream.rs
use crate::event::{Error, EventStreamConfig, Result}; use futures::{channel::{mpsc as futures_mpsc, mpsc::UnboundedSender}, stream::StreamExt}; use rants::{error::Error as RantsError, native_tls::TlsConnector, Client, ...
}); Ok(NatsMessageStream(tx)) } /// Queues a NATS message to be published pub fn send(&self, event_packet: NatsMessage) { trace!("Queueing message: {:?}", event_packet); if let Err(e) = self.0.unbounded_send(event_packet) { error!("Failed to queue message, err: ...
} } }
random_line_split
nats_message_stream.rs
use crate::event::{Error, EventStreamConfig, Result}; use futures::{channel::{mpsc as futures_mpsc, mpsc::UnboundedSender}, stream::StreamExt}; use rants::{error::Error as RantsError, native_tls::TlsConnector, Client, ...
(&self, event_packet: NatsMessage) { trace!("Queueing message: {:?}", event_packet); if let Err(e) = self.0.unbounded_send(event_packet) { error!("Failed to queue message, err: {}", e); } } }
send
identifier_name
env.rs
use crate::wrapper::binary::ErlNifBinary; use crate::wrapper::{ERL_NIF_BIN2TERM_SAFE, NIF_ENV, NIF_TERM}; use std::mem::MaybeUninit; pub unsafe fn binary_to_term(env: NIF_ENV, data: &[u8], safe: bool) -> Option<(NIF_TERM, usize)> { let opts = if safe
else { 0 }; let mut result = MaybeUninit::uninit(); let read_count = rustler_sys::enif_binary_to_term(env, data.as_ptr(), data.len(), result.as_mut_ptr(), opts); if read_count == 0 { return None; } Some((result.assume_init(), read_count)) } pub unsafe fn term_to_binary(env: NIF_...
{ ERL_NIF_BIN2TERM_SAFE }
conditional_block
env.rs
use crate::wrapper::binary::ErlNifBinary; use crate::wrapper::{ERL_NIF_BIN2TERM_SAFE, NIF_ENV, NIF_TERM}; use std::mem::MaybeUninit; pub unsafe fn binary_to_term(env: NIF_ENV, data: &[u8], safe: bool) -> Option<(NIF_TERM, usize)>
pub unsafe fn term_to_binary(env: NIF_ENV, term: NIF_TERM) -> Option<ErlNifBinary> { let mut binary = MaybeUninit::uninit(); let success = rustler_sys::enif_term_to_binary(env, term, binary.as_mut_ptr()); if success == 0 { return None; } Some(binary.assume_init()) }
{ let opts = if safe { ERL_NIF_BIN2TERM_SAFE } else { 0 }; let mut result = MaybeUninit::uninit(); let read_count = rustler_sys::enif_binary_to_term(env, data.as_ptr(), data.len(), result.as_mut_ptr(), opts); if read_count == 0 { return None; } Some((result.assume_init(), read...
identifier_body
env.rs
use crate::wrapper::binary::ErlNifBinary; use crate::wrapper::{ERL_NIF_BIN2TERM_SAFE, NIF_ENV, NIF_TERM}; use std::mem::MaybeUninit; pub unsafe fn
(env: NIF_ENV, data: &[u8], safe: bool) -> Option<(NIF_TERM, usize)> { let opts = if safe { ERL_NIF_BIN2TERM_SAFE } else { 0 }; let mut result = MaybeUninit::uninit(); let read_count = rustler_sys::enif_binary_to_term(env, data.as_ptr(), data.len(), result.as_mut_ptr(), opts); if read_count ==...
binary_to_term
identifier_name
env.rs
use crate::wrapper::binary::ErlNifBinary; use crate::wrapper::{ERL_NIF_BIN2TERM_SAFE, NIF_ENV, NIF_TERM}; use std::mem::MaybeUninit; pub unsafe fn binary_to_term(env: NIF_ENV, data: &[u8], safe: bool) -> Option<(NIF_TERM, usize)> {
let mut result = MaybeUninit::uninit(); let read_count = rustler_sys::enif_binary_to_term(env, data.as_ptr(), data.len(), result.as_mut_ptr(), opts); if read_count == 0 { return None; } Some((result.assume_init(), read_count)) } pub unsafe fn term_to_binary(env: NIF_ENV, term: NIF...
let opts = if safe { ERL_NIF_BIN2TERM_SAFE } else { 0 };
random_line_split
main.rs
-h 720 - |\\ ffmpeg -f rawvideo -pixel_format gray -video_size 1280x720 -i - out.mkv "; macro_rules! printerr { ($fmt:expr) => (::std::io::Write ::write_fmt(&mut ::std::io::stderr(), format_args!(concat!($fmt, "\n"))) .unwrap()); ($fmt:expr, $($arg:tt)*) => (::std::i...
(&mut self, frame: &[u8]) -> &[u8] { debug_assert_eq!(frame.len(), self.orig_width * self.orig_height); self.resizer.run(frame, &mut self.img); unsafe { let vram = aa_image(self.ctx) as *mut u8; ptr::copy_nonoverlapping(self.img.as_ptr(), vram, self.img.len()); ...
render
identifier_name
main.rs
1280 -h 720 - |\\ ffmpeg -f rawvideo -pixel_format gray -video_size 1280x720 -i - out.mkv "; macro_rules! printerr { ($fmt:expr) => (::std::io::Write ::write_fmt(&mut ::std::io::stderr(), format_args!(concat!($fmt, "\n"))) .unwrap()); ($fmt:expr, $($arg:tt)*) => (::s...
#[repr(C)] struct aa_driver; #[repr(C)] struct aa_font; #[repr(C)] #[derive(Clone)] #[allow(raw_pointer_derive)] struct aa_hardware_params { font: *const aa_font, supported: c_int, minwidth: c_int, minheight: c_int, maxwidth: c_int, maxheight: c_int, recwidth: c_int, recheight: c_int,...
} #[repr(C)] struct aa_context;
random_line_split
main.rs
-h 720 - |\\ ffmpeg -f rawvideo -pixel_format gray -video_size 1280x720 -i - out.mkv "; macro_rules! printerr { ($fmt:expr) => (::std::io::Write ::write_fmt(&mut ::std::io::stderr(), format_args!(concat!($fmt, "\n"))) .unwrap()); ($fmt:expr, $($arg:tt)*) => (::std::i...
; let filter_radius = (filter_support * filter_scale).ceil(); let mut coeffs = Vec::with_capacity(s2); for x2 in 0..s2 { let x1 = (x2 as f32 + 0.5) * ratio - 0.5; let left = (x1 - filter_radius).ceil() as isize; let left = Self::clamp(left, 0, s1 as isize - 1)...
{ 1.0 }
conditional_block
data_loader.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/. */ extern crate hyper; use ipc_channel::ipc; use net_traits::LoadConsumer::Channel; use net_traits::ProgressMsg::{Pa...
() { assert_parse("data:application/octet-stream;base64,C62+7w==", Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_owned()), vec!()))), None, Some(vec!(0x0B, 0xAD, 0xBE, 0xEF))); } #[test] fn base64_charset() { assert_parse("data:text/plain;charset=koi8-r;ba...
base64_ct
identifier_name
data_loader.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/. */ extern crate hyper; use ipc_channel::ipc; use net_traits::LoadConsumer::Channel; use net_traits::ProgressMsg::{Pa...
{ assert_parse("data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("koi8-r".to_owned())))))), Some("koi8-r".to_owned()), Some(vec!(0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4...
identifier_body
data_loader.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/. */ extern crate hyper; use ipc_channel::ipc;
use self::hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; #[cfg(test)] fn assert_parse(url: &'static str, content_type: Option<ContentType>, charset: Option<String>, data: Option<Vec<u8>>) { use net::data_loader::load; use net::mime_cl...
use net_traits::LoadConsumer::Channel; use net_traits::ProgressMsg::{Payload, Done}; use net_traits::{LoadData, LoadContext, NetworkError}; use self::hyper::header::ContentType;
random_line_split
data_loader.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/. */ extern crate hyper; use ipc_channel::ipc; use net_traits::LoadConsumer::Channel; use net_traits::ProgressMsg::{Pa...
} } #[test] fn empty_invalid() { assert_parse("data:", None, None, None); } #[test] fn plain() { assert_parse( "data:,hello%20world", Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))), S...
{ assert_eq!(progress, Payload(dat)); assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(()))); }
conditional_block
cfg-eval-inner.rs
// compile-flags: -Z span-debug // aux-build:test-macros.rs // check-pass #![feature(cfg_eval)] #![feature(custom_inner_attributes)] #![feature(stmt_expr_attributes)] #![feature(rustc_attrs)] #![no_std] // Don't load unnecessary hygiene information from std extern crate std; #[macro_use] extern crate test_macros; s...
{ field: [u8; { #![cfg_attr(not(FALSE), rustc_dummy(another_cursed_inner))] 1 }] } 0 }]> { #![cfg_eval] #![print_attr] #![cfg_attr(not(FALSE), rustc_dummy(evaluated_attr))] fn bar() { #[cfg(FALSE)] let a = 1; } } fn main() {}
Inner
identifier_name
cfg-eval-inner.rs
// compile-flags: -Z span-debug // aux-build:test-macros.rs // check-pass #![feature(cfg_eval)] #![feature(custom_inner_attributes)] #![feature(stmt_expr_attributes)] #![feature(rustc_attrs)] #![no_std] // Don't load unnecessary hygiene information from std extern crate std; #[macro_use] extern crate test_macros; s...
fn bar() { #[cfg(FALSE)] let a = 1; } } fn main() {}
#![cfg_eval] #![print_attr] #![cfg_attr(not(FALSE), rustc_dummy(evaluated_attr))]
random_line_split
struct.rs
mod my { // A public struct with a public field of generic type `T` pub struct WhiteBox<T> { pub contents: T, } // A public struct with a private field of generic type `T` #[allow(dead_code)] pub struct BlackBox<T> { contents: T, } impl<T> BlackBox<T> { // A pub...
} } fn main() { // Public structs with public fields can be constructed as usual let white_box = my::WhiteBox { contents: "public information" }; // and their fields can be normally accessed. println!("The white box contains: {}", white_box.contents); // Public structs with private fields can...
pub fn new(contents: T) -> BlackBox<T> { BlackBox { contents: contents, } }
random_line_split
struct.rs
mod my { // A public struct with a public field of generic type `T` pub struct WhiteBox<T> { pub contents: T, } // A public struct with a private field of generic type `T` #[allow(dead_code)] pub struct BlackBox<T> { contents: T, } impl<T> BlackBox<T> { // A pub...
() { // Public structs with public fields can be constructed as usual let white_box = my::WhiteBox { contents: "public information" }; // and their fields can be normally accessed. println!("The white box contains: {}", white_box.contents); // Public structs with private fields cannot be construct...
main
identifier_name
designators.rs
use parser::ArgumentSplitter; use shell::Shell; use std::{borrow::Cow, str}; bitflags! { struct Flags: u8 { const DQUOTE = 1; const SQUOTE = 2; const DESIGN = 4; } } #[derive(Debug)] enum Token<'a> { Designator(&'a str), Text(&'a str), } struct DesignatorSearcher<'a> { dat...
(text: &str) -> &str { let bytes = text.as_bytes(); bytes.iter() // Obtain position of the first space character, .position(|&x| x == b' ') // and then obtain the arguments to the command. .and_then(|fp| bytes[fp+1..].iter() // Find the position of the first character i...
args
identifier_name
designators.rs
use parser::ArgumentSplitter; use shell::Shell; use std::{borrow::Cow, str}; bitflags! { struct Flags: u8 { const DQUOTE = 1; const SQUOTE = 2; const DESIGN = 4; } } #[derive(Debug)] enum Token<'a> { Designator(&'a str), Text(&'a str), } struct DesignatorSearcher<'a> { dat...
// Then slice the argument string from the original command. .map(|sp| &text[fp+sp+1..])) // Unwrap the arguments string if it exists, else return the original string. .unwrap_or(text) } fn first_arg<'a>(text: &'a str) -> &'a str { ArgumentSplitter::new(text).nth(1).unwrap_or(text...
.position(|&x| x == b' ') // and then obtain the arguments to the command. .and_then(|fp| bytes[fp+1..].iter() // Find the position of the first character in the first argument. .position(|&x| x != b' ')
random_line_split
entity.rs
use core::{Sprite, Matter}; /// Events. pub enum Event { /// When player 'contacts' (press space in front of) the object Contact, /// When the entity move Movement, /// When the entity collides with player PlayerCollision, /// When the entity is destroyed Destroy, // TODO: Add more ...
(pub i64); /// An entity, a dynamic in-game object with non-trivial functionality pub trait Entity: Sprite + Matter { /// Get the ID of the given entity fn id(&self) -> Id; /// Is the entity solid at point (x, y) relative to the position? fn is_solid(&self, x: i16, y: i16) -> bool; /// The default ...
Id
identifier_name
entity.rs
use core::{Sprite, Matter}; /// Events. pub enum Event { /// When player 'contacts' (press space in front of) the object Contact, /// When the entity move Movement, /// When the entity collides with player PlayerCollision, /// When the entity is destroyed Destroy, // TODO: Add more ...
// Probably need more methods. }
random_line_split
entity.rs
use core::{Sprite, Matter}; /// Events. pub enum Event { /// When player 'contacts' (press space in front of) the object Contact, /// When the entity move Movement, /// When the entity collides with player PlayerCollision, /// When the entity is destroyed Destroy, // TODO: Add more ...
} } // Probably need more methods. }
{}
conditional_block
fuse.rs
use core::pin::Pin; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`fuse`](super::StreamExt::fuse) method. #[derive(Debug)] ...
(&self) -> (usize, Option<usize>) { if self.done { (0, Some(0)) } else { self.stream.size_hint() } } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S: Stream + Sink<Item>, Item> Sink<Item> for Fuse<S> { type Error = S::Error...
size_hint
identifier_name
fuse.rs
use core::pin::Pin; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`fuse`](super::StreamExt::fuse) method. #[derive(Debug)] ...
else { self.stream.size_hint() } } } // Forwarding impl of Sink from the underlying stream #[cfg(feature = "sink")] impl<S: Stream + Sink<Item>, Item> Sink<Item> for Fuse<S> { type Error = S::Error; delegate_sink!(stream, Item); }
{ (0, Some(0)) }
conditional_block
fuse.rs
use core::pin::Pin; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`fuse`](super::StreamExt::fuse) method. #[derive(Debug)] ...
pub(crate) fn new(stream: St) -> Self { Self { stream, done: false } } /// Returns whether the underlying stream has finished or not. /// /// If this method returns `true`, then all future calls to poll are /// guaranteed to return `None`. If this returns `false`, then the /// under...
done: bool, } } impl<St> Fuse<St> {
random_line_split
fuse.rs
use core::pin::Pin; use futures_core::ready; use futures_core::stream::{FusedStream, Stream}; use futures_core::task::{Context, Poll}; #[cfg(feature = "sink")] use futures_sink::Sink; use pin_project_lite::pin_project; pin_project! { /// Stream for the [`fuse`](super::StreamExt::fuse) method. #[derive(Debug)] ...
} impl<S: Stream> Stream for Fuse<S> { type Item = S::Item; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> { let this = self.project(); if *this.done { return Poll::Ready(None); } let item = ready!(this.stream.poll_next(cx)); ...
{ self.done }
identifier_body
timer.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 ...
<T>(&mut self, data: *T) { uvll::set_data_for_uv_handle(self.handle, data); } } impl HomingIO for TimerWatcher { fn home<'r>(&'r mut self) -> &'r mut HomeHandle { &mut self.home } } impl UvHandle<uvll::uv_timer_t> for TimerWatcher { fn uv_handle(&self) -> *uvll::uv_timer_t { self.handle } } impl ...
set_data
identifier_name
timer.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 ...
timer.period(1000) }; assert_eq!(port.recv_opt(), Err(())); } #[test] fn receiver_goes_away_oneshot() { let mut timer1 = TimerWatcher::new(local_loop()); drop(timer1.oneshot(1)); let mut timer2 = TimerWatcher::new(local_loop()); // while sleeping,...
let port = { let mut timer = TimerWatcher::new(local_loop());
random_line_split
timer.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 ...
pub fn new_home(loop_: &Loop, home: HomeHandle) -> TimerWatcher { let handle = UvHandle::alloc(None::<TimerWatcher>, uvll::UV_TIMER); assert_eq!(unsafe { uvll::uv_timer_init(loop_.handle, handle) }, 0); TimerWatcher { handle: handle, action: None, blocke...
{ let handle = io.make_handle(); let me = box TimerWatcher::new_home(&io.loop_, handle); me.install() }
identifier_body
registry.rs
use std::collections::HashMap; use std::io::Write; use serialize::json::ToJson; use template::{Template, TemplateError}; use render::{Renderable, RenderError, RenderContext}; use helpers::{HelperDef}; use context::{Context}; use helpers; use support::str::StringWriter; pub struct Registry { templates: HashMap<St...
} } #[cfg(test)] mod test { use template::{Template}; use registry::{Registry}; use render::{RenderContext, Renderable, RenderError, Helper}; use helpers::{HelperDef}; use context::{Context}; use support::str::StringWriter; #[derive(Clone, Copy)] struct DummyHelper; impl Help...
{ Err(RenderError{ desc: "Template not found." }) }
conditional_block
registry.rs
use std::collections::HashMap; use std::io::Write; use serialize::json::ToJson; use template::{Template, TemplateError}; use render::{Renderable, RenderError, RenderContext}; use helpers::{HelperDef}; use context::{Context}; use helpers; use support::str::StringWriter; pub struct Registry { templates: HashMap<St...
let mut sw = StringWriter::new(); let context = Context::null(); { r.renderw("index", &context, &mut sw).ok().unwrap(); } assert_eq!("<h1></h1>".to_string(), sw.to_string()); } }
r.register_template("index", t.clone());
random_line_split
registry.rs
use std::collections::HashMap; use std::io::Write; use serialize::json::ToJson; use template::{Template, TemplateError}; use render::{Renderable, RenderError, RenderContext}; use helpers::{HelperDef}; use context::{Context}; use helpers; use support::str::StringWriter; pub struct Registry { templates: HashMap<St...
pub fn unregister_template(&mut self, name: &String) { self.templates.remove(name); } pub fn register_helper(&mut self, name: &str, def: Box<HelperDef +'static>) -> Option<Box<HelperDef +'static>> { self.helpers.insert(name.to_string(), def) } pub fn get_template(&self, name: &St...
{ let t = Template::compile(tpl_str); if let Ok(tpl) = t { self.templates.insert(name.to_string(), tpl); Ok(()) } else { Err(t.err().unwrap()) } }
identifier_body
registry.rs
use std::collections::HashMap; use std::io::Write; use serialize::json::ToJson; use template::{Template, TemplateError}; use render::{Renderable, RenderError, RenderContext}; use helpers::{HelperDef}; use context::{Context}; use helpers; use support::str::StringWriter; pub struct Registry { templates: HashMap<St...
() -> Registry { let mut r = Registry { templates: HashMap::new(), helpers: HashMap::new() }; r.register_helper("if", Box::new(helpers::IF_HELPER)); r.register_helper("unless", Box::new(helpers::UNLESS_HELPER)); r.register_helper("each", Box::new(helpers:...
new
identifier_name
testutil.rs
use std::sync::Arc; use super::PyExecutor; use cpython::{exc, py_class, PyErr, PyObject, PyResult, PyString}; use parking_lot::Mutex; use testutil_mock::{StubCAS, StubCASBuilder};
data builder: Arc<Mutex<Option<StubCASBuilder>>>; def always_errors(&self) -> PyResult<PyObject> { let mut builder_opt = self.builder(py).lock(); let builder = builder_opt .take() .ok_or_else(|| PyErr::new::<exc::Exception, _>(py, (PyString::new(py, "unable to unwrap StubCASBuilder"),)))? .a...
py_class!(pub class PyStubCASBuilder |py| {
random_line_split
html.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/. */ #![allow(unrooted_must_root)] use document_loader::DocumentLoader; use dom::bindings::codegen::Bindings::Document...
(&mut self, parent: JS<Node>, child: NodeOrText<JS<Node>>) { let parent: Root<Node> = parent.root(); let child = self.get_or_create(child); // FIXME(#3701): Use a simpler algorithm and merge adjacent text nodes assert!(parent.r().AppendChild(child.r()).is_ok()); } fn append_doc...
append
identifier_name
html.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/. */ #![allow(unrooted_must_root)] use document_loader::DocumentLoader; use dom::bindings::codegen::Bindings::Document...
use dom::characterdata::CharacterDataTypeId; use dom::comment::Comment; use dom::document::Document; use dom::document::{DocumentSource, IsHTMLDocument}; use dom::documenttype::DocumentType; use dom::element::{Element, ElementCreator}; use dom::htmlscriptelement::HTMLScriptElement; use dom::node::{Node, NodeTypeId}; us...
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLFormElementDerived}; use dom::bindings::codegen::InheritTypes::{HTMLScriptElementCast, HTMLTemplateElementCast}; use dom::bindings::codegen::InheritTypes::{NodeCast, ProcessingInstructionCast}; use dom::bindings::js::{JS, Root}; use dom::bindings::js::{RootedR...
random_line_split
html.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/. */ #![allow(unrooted_must_root)] use document_loader::DocumentLoader; use dom::bindings::codegen::Bindings::Document...
} impl<'a> Serializable for &'a Node { fn serialize<'wr, Wr: Write>(&self, serializer: &mut Serializer<'wr, Wr>, traversal_scope: TraversalScope) -> io::Result<()> { let node = *self; match (traversal_scope, node.type_id()) { (_, NodeTypeId::Element(..)...
{ let new_parent = new_parent.root(); let new_parent = new_parent.r(); let old_parent = node.root(); let old_parent = old_parent.r(); while let Some(ref child) = old_parent.GetFirstChild() { new_parent.AppendChild(child.r()).unwrap(); } }
identifier_body
text.rs
extern crate three; fn main() { let mut window = three::Window::new("Three-rs text example"); window.scene.background = three::Background::Color(0x111111); let center = [0.0, 0.0]; let yextent = 1.0; let zrange = -1.0.. 1.0; let camera = window.factory.orthographic_camera(center, yextent, zra...
env!("CARGO_MANIFEST_DIR") )); let karla = window.factory.load_font_karla(); let mut counter_text = window.factory.ui_text(&deja_vu, ""); counter_text.set_font_size(20.0); window.scene.add(&counter_text); let mut greeting = window.factory.ui_text(&karla, "Hello World!"); greeting.s...
let deja_vu = window.factory.load_font(format!( "{}/data/fonts/DejaVuSans.ttf",
random_line_split
text.rs
extern crate three; fn main()
let mut greeting = window.factory.ui_text(&karla, "Hello World!"); greeting.set_font_size(80.0); greeting.set_pos([100.0, 100.0]); greeting.set_color(0xFF0000); window.scene.add(&greeting); let mut lenny = window.factory.ui_text(&deja_vu, "( ͡° ͜ʖ ͡°)"); lenny.set_font_size(60.0); lenny...
{ let mut window = three::Window::new("Three-rs text example"); window.scene.background = three::Background::Color(0x111111); let center = [0.0, 0.0]; let yextent = 1.0; let zrange = -1.0 .. 1.0; let camera = window.factory.orthographic_camera(center, yextent, zrange); let deja_vu = windo...
identifier_body
text.rs
extern crate three; fn
() { let mut window = three::Window::new("Three-rs text example"); window.scene.background = three::Background::Color(0x111111); let center = [0.0, 0.0]; let yextent = 1.0; let zrange = -1.0.. 1.0; let camera = window.factory.orthographic_camera(center, yextent, zrange); let deja_vu = win...
main
identifier_name
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use diem_config::network_id::NetworkContext; use diem_crypto::{test_utils::TEST_SEED, x25519, Uniform as _}; use diem_logger::prelude::*; use diem_types::network_address::NetworkAddress; use futures::{ futur...
{ pub tcp_addr: Option<NetworkAddress>, pub tcp_noise_addr: Option<NetworkAddress>, pub msg_lens: Option<Vec<usize>>, } fn parse_addr(s: OsString) -> NetworkAddress { s.to_str() .expect("Error: Address should be valid Unicode") .parse() .expect("Error: Address should be a multiadd...
Args
identifier_name
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use diem_config::network_id::NetworkContext; use diem_crypto::{test_utils::TEST_SEED, x25519, Uniform as _}; use diem_logger::prelude::*; use diem_types::network_address::NetworkAddress; use futures::{ futur...
"Connection upgrade failed {:?}", e), }; } Err(e) => error!( error =?e, "Stream failed {:?}", e), } }) .await } pub fn start_stream_server<T, L, I, S, E>( executor: &H...
{ // Wait for next inbound connection, this simulated the TransportHandler // which is single-threaded asynchronous accepting new connections. server_listener .for_each_concurrent(None, |result| async { match result { Ok((f_stream, _)) => { match f_str...
identifier_body
lib.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 #![forbid(unsafe_code)] use diem_config::network_id::NetworkContext; use diem_crypto::{test_utils::TEST_SEED, x25519, Uniform as _}; use diem_logger::prelude::*; use diem_types::network_address::NetworkAddress; use futures::{ futur...
} } /// Build a MemorySocket + Noise transport pub fn build_memsocket_noise_transport() -> impl Transport<Output = NoiseStream<MemorySocket>> { MemoryTransport::default().and_then(move |socket, addr, origin| async move { let mut rng: StdRng = SeedableRng::from_seed(TEST_SEED); let private = x25...
tcp_addr: env::var_os("TCP_ADDR").map(parse_addr), tcp_noise_addr: env::var_os("TCP_NOISE_ADDR").map(parse_addr), msg_lens: env::var_os("MSG_LENS").map(parse_msg_lens), }
random_line_split
timer.rs
extern crate time; const SEC_MULTIPLIER:u64 = 1000 * 1000 * 1000; const MIN_MULTIPLIER:u64 = 60 * SEC_MULTIPLIER; const HR_MULTIPLIER:u64 = 60 * MIN_MULTIPLIER; #[deriving(Copy)] pub struct Timer { start_time: u64, end_time: u64 } impl Timer { pub fn new() -> Timer { Timer { start_time: 0, end_ti...
index += 1; } return ret_val } #[test] fn format_number_test() { let num1 = 123456789; let num2 = 12345678; let num3 = 1234; assert!(format_number(num1) == "123,456,789"); assert!(format_number(num2) == "12,345,678"); assert!(format_number(num3) == "1,234"); } #[test] fn for...
{ ret_val.push_str(","); }
conditional_block
timer.rs
extern crate time; const SEC_MULTIPLIER:u64 = 1000 * 1000 * 1000; const MIN_MULTIPLIER:u64 = 60 * SEC_MULTIPLIER; const HR_MULTIPLIER:u64 = 60 * MIN_MULTIPLIER; #[deriving(Copy)] pub struct
{ start_time: u64, end_time: u64 } impl Timer { pub fn new() -> Timer { Timer { start_time: 0, end_time: 0} } pub fn start(&mut self) -> () { self.start_time = time::precise_time_ns(); } pub fn end(&mut self) -> () { self.end_time = time::precise_time_ns(); } ...
Timer
identifier_name
timer.rs
extern crate time; const SEC_MULTIPLIER:u64 = 1000 * 1000 * 1000; const MIN_MULTIPLIER:u64 = 60 * SEC_MULTIPLIER; const HR_MULTIPLIER:u64 = 60 * MIN_MULTIPLIER; #[deriving(Copy)] pub struct Timer { start_time: u64, end_time: u64 } impl Timer { pub fn new() -> Timer { Timer { start_time: 0, end_ti...
} else if seconds > 0 { time_string.push_str(" sec"); } else { time_string.push_str(" ns"); } //time_string += format!(" ({})", total_time); return time_string; } fn format_number(num: u64) -> String { let repr = num.to_string(); let repr = repr.as_slice(); let mut ret...
} else if minutes > 0 { time_string.push_str(" min");
random_line_split
timer.rs
extern crate time; const SEC_MULTIPLIER:u64 = 1000 * 1000 * 1000; const MIN_MULTIPLIER:u64 = 60 * SEC_MULTIPLIER; const HR_MULTIPLIER:u64 = 60 * MIN_MULTIPLIER; #[deriving(Copy)] pub struct Timer { start_time: u64, end_time: u64 } impl Timer { pub fn new() -> Timer { Timer { start_time: 0, end_ti...
pub fn end(&mut self) -> () { self.end_time = time::precise_time_ns(); } pub fn get_time_string(&mut self) -> String { return format_as_time(self.get_total_time()); } pub fn get_total_time(&mut self) -> u64 { return self.end_time - self.start_time; } pub fn show_time...
{ self.start_time = time::precise_time_ns(); }
identifier_body
byte-string-literals.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 ...
{ b"\f"; //~ ERROR unknown byte escape b"\x0Z"; //~ ERROR illegal character in numeric character escape: Z b"é"; //~ ERROR byte constant must be ASCII b"a //~ ERROR unterminated double quote byte string }
identifier_body
byte-string-literals.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
// ignore-tidy-tab static FOO: &'static [u8] = b"\f"; //~ ERROR unknown byte escape pub fn main() { b"\f"; //~ ERROR unknown byte escape b"\x0Z"; //~ ERROR illegal character in numeric character escape: Z b"é"; //~ ERROR byte constant must be ASCII b"a //~ ERROR unterminated double quote byte str...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
byte-string-literals.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 ...
() { b"\f"; //~ ERROR unknown byte escape b"\x0Z"; //~ ERROR illegal character in numeric character escape: Z b"é"; //~ ERROR byte constant must be ASCII b"a //~ ERROR unterminated double quote byte string }
main
identifier_name
json.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
} impl Json { pub fn decref(val: Json) { unsafe{SCJsonDecref(val.js)}; } pub fn object() -> Json { return Json{ js: unsafe{json_object()}, } } pub fn array() -> Json { return Json{ js: unsafe{json_array()}, } } pub fn strin...
} pub struct Json { pub js: *mut JsonT,
random_line_split
json.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
else { safe.push(*c); } } match CString::new(safe) { Ok(cstr) => cstr, _ => { CString::new("<failed to encode string>").unwrap() } } } #[cfg(test)] mod tests { use json::to_cstring; #[test] fn test_to_string() { assert_eq!("A\\x...
{ safe.extend(format!("\\x{:02x}", *c).as_bytes()); }
conditional_block
json.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
(val: Json) { unsafe{SCJsonDecref(val.js)}; } pub fn object() -> Json { return Json{ js: unsafe{json_object()}, } } pub fn array() -> Json { return Json{ js: unsafe{json_array()}, } } pub fn string(val: &str) -> Json { re...
decref
identifier_name
json.rs
/* Copyright (C) 2017 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
pub fn array_append_string(&self, val: &str) { unsafe { json_array_append_new(self.js, json_string(to_cstring(val.as_bytes()).as_ptr())); } } } /// Convert an array of bytes into an ascii printable string replacing /// non-printable characters (including NULL) with hex value. /// /...
{ unsafe { json_array_append_new(self.js, val.js); } }
identifier_body
mod.rs
// Copyright 2015, 2016 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 la...
} // private helpers impl<L: LightChainClient> LightSync<L> { // Begins a search for the common ancestor and our best block. // does not lock state, instead has a mutable reference to it passed. fn begin_search(&self, state: &mut SyncState) { if let None = *self.best_seen.lock() { // no peers. *state = Sy...
{ self.maintain_sync(ctx); }
identifier_body
mod.rs
// Copyright 2015, 2016 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 la...
} other => other, } } } // synchronization state machine. #[derive(Debug)] enum SyncState { // Idle (waiting for peers) or at chain head. Idle, // searching for common ancestor with best chain. // queue should be cleared at this phase. AncestorSearch(AncestorSearch), // Doing sync rounds. Rounds(SyncRo...
match dispatcher(req.clone()) { Some(req_id) => AncestorSearch::Awaiting(req_id, start, req), None => AncestorSearch::Queued(start), }
random_line_split
mod.rs
// Copyright 2015, 2016 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 la...
(&self, other: &Self) -> ::std::cmp::Ordering { self.head_td.cmp(&other.head_td) } } struct Peer { status: ChainInfo, } impl Peer { // Create a new peer. fn new(chain_info: ChainInfo) -> Self { Peer { status: chain_info, } } } // search for a common ancestor with the best chain. #[derive(Debug)] enum A...
cmp
identifier_name
main.rs
//! Run the static site generator. mod cli; // Standard library use std::io::prelude::*; // First party use crate::cli::{cli, Command}; fn main() { if let Err(reason) = run() { // if this fails, we literally can't do a thing except panic. write!(std::io::stderr(), "failure: {}", reason).unwrap()...
() -> Result<(), String> { match cli() { Command::Init { site_directory } => lightning::init(site_directory), Command::Build { site_directory, local: _, } => lightning::build(site_directory), Command::Create { template: _ } => lightning::create(), Comm...
run
identifier_name
main.rs
//! Run the static site generator. mod cli; // Standard library use std::io::prelude::*; // First party use crate::cli::{cli, Command}; fn main() { if let Err(reason) = run() { // if this fails, we literally can't do a thing except panic. write!(std::io::stderr(), "failure: {}", reason).unwrap()...
match cli() { Command::Init { site_directory } => lightning::init(site_directory), Command::Build { site_directory, local: _, } => lightning::build(site_directory), Command::Create { template: _ } => lightning::create(), Command::Serve {} => lightning:...
/// (This is a standard Rust pattern to support the use of `try~`/`?`. We're /// not doing that yet, but I expect we might eventually; this is convenient.) fn run() -> Result<(), String> {
random_line_split
main.rs
//! Run the static site generator. mod cli; // Standard library use std::io::prelude::*; // First party use crate::cli::{cli, Command}; fn main()
/// Define a `Result`-returning function to run the app. /// /// (This is a standard Rust pattern to support the use of `try~`/`?`. We're /// not doing that yet, but I expect we might eventually; this is convenient.) fn run() -> Result<(), String> { match cli() { Command::Init { site_directory } => lightn...
{ if let Err(reason) = run() { // if this fails, we literally can't do a thing except panic. write!(std::io::stderr(), "failure: {}", reason).unwrap(); std::process::exit(1); } }
identifier_body
bezier.rs
//! https://en.wikipedia.org/wiki/B%C3%A9zier_curve use turtle::{Turtle, Point}; struct CubicBezier { point0: Point, point1: Point, point2: Point, point3: Point, } impl CubicBezier { /// Returns the value of this curve at the given point pub fn at(&self, t: f64) -> Point { let &Self {...
turtle.pen_up(); turtle.go_to(start); turtle.pen_down(); let samples = 100; for i in 0..samples { let t = i as f64 / samples as f64; let point = curve.at(t); turtle.go_to(point); } }
point2: Point {x: 100.0, y: -500.0}, point3: Point {x: 300.0, y: 200.0}, }; let start = curve.at(0.0);
random_line_split
bezier.rs
//! https://en.wikipedia.org/wiki/B%C3%A9zier_curve use turtle::{Turtle, Point}; struct CubicBezier { point0: Point, point1: Point, point2: Point, point3: Point, } impl CubicBezier { /// Returns the value of this curve at the given point pub fn
(&self, t: f64) -> Point { let &Self {point0, point1, point2, point3} = self; // Copying the formula from here verbatim: // https://en.wikipedia.org/wiki/B%C3%A9zier_curve#Cubic_B%C3%A9zier_curves (1.0 - t).powi(3) * point0 + 3.0*(1.0 - t)*(1.0 - t)*t*point1 + 3.0...
at
identifier_name
bezier.rs
//! https://en.wikipedia.org/wiki/B%C3%A9zier_curve use turtle::{Turtle, Point}; struct CubicBezier { point0: Point, point1: Point, point2: Point, point3: Point, } impl CubicBezier { /// Returns the value of this curve at the given point pub fn at(&self, t: f64) -> Point { let &Self {...
} }
{ let mut turtle = Turtle::new(); let curve = CubicBezier { point0: Point {x: -200.0, y: -100.0}, point1: Point {x: -100.0, y: 400.0}, point2: Point {x: 100.0, y: -500.0}, point3: Point {x: 300.0, y: 200.0}, }; let start = curve.at(0.0); turtle.pen_up(); turtle....
identifier_body
fake_sign.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...
(request: CallRequest, gas_cap: bool) -> Result<SignedTransaction, Error> { let max_gas = 50_000_000.into(); let gas = match request.gas { Some(gas) if gas_cap && gas > max_gas => { warn!("Gas limit capped to {} (from {})", max_gas, gas); max_gas } Some(gas) => gas, None if gas_cap => max_gas, None =>...
sign_call
identifier_name
fake_sign.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...
}.fake_sign(from)) }
{ let max_gas = 50_000_000.into(); let gas = match request.gas { Some(gas) if gas_cap && gas > max_gas => { warn!("Gas limit capped to {} (from {})", max_gas, gas); max_gas } Some(gas) => gas, None if gas_cap => max_gas, None => U256::from(2) << 50, }; let from = request.from.unwrap_or(0.into()); ...
identifier_body
fake_sign.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...
use jsonrpc_core::Error; use v1::helpers::CallRequest; pub fn sign_call(request: CallRequest, gas_cap: bool) -> Result<SignedTransaction, Error> { let max_gas = 50_000_000.into(); let gas = match request.gas { Some(gas) if gas_cap && gas > max_gas => { warn!("Gas limit capped to {} (from {})", max_gas, gas); ...
// along with Parity. If not, see <http://www.gnu.org/licenses/>. use ethcore::transaction::{Transaction, SignedTransaction, Action}; use bigint::prelude::U256;
random_line_split
vga.rs
/******************************************************************************* * * kit/kernel/terminal/vga.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more informatio...
, _ => { self.put_here(byte); self.col += 1; if self.col >= self.config.width { self.new_line(); } } } Ok(()) } fn flush(&mut self) -> fmt::Result { self.update_cursor(); ...
{ if self.col > 0 { self.col -= 1; } self.put_here(' ' as u8); }
conditional_block
vga.rs
/******************************************************************************* * * kit/kernel/terminal/vga.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more informatio...
} impl fmt::Write for Vga { fn write_char(&mut self, ch: char) -> fmt::Result { let mut buf = [0; 4]; self.write_raw_bytes(ch.encode_utf8(&mut buf).as_bytes())?; self.flush()?; Ok(()) } fn write_str(&mut self, s: &str) -> fmt::Result { self.write_raw_bytes(s.as_byt...
{ self.update_cursor(); Ok(()) }
identifier_body
vga.rs
/******************************************************************************* * * kit/kernel/terminal/vga.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more informatio...
(&self) -> VgaConfig { self.config } pub fn color(c: Color) -> u8 { c as u8 } pub fn attr(fg: Color, bg: Color) -> u8 { Vga::color(fg) | (Vga::color(bg) << 4) } fn update_attr(&mut self) { self.attr = Vga::attr(self.fg, self.bg); } fn update_cursor(&mu...
config
identifier_name
vga.rs
/******************************************************************************* * * kit/kernel/terminal/vga.rs * * vim:ft=rust:ts=4:sw=4:et:tw=80 * * Copyright (C) 2015-2021, Devyn Cairns * Redistribution of this file is permitted under the terms of the simplified * BSD license. See LICENSE for more informatio...
self.attr = Vga::attr(self.fg, self.bg); } fn update_cursor(&mut self) { unsafe fn outb(byte: u8, port: u16) { asm!("out %al, %dx", in("al") byte, in("dx") port, options(att_syntax)); } let pos: u16 = ((self.row * self.config.width) + self.col) as u16; unsa...
random_line_split
client_simple.rs
//! An example of usage of the `solicit::client::SimpleClient` API. //! //! This is a simple implementation of an HTTP/2 client, built on top of the API of `solicit::http` //! that performs all IO in the main thread. extern crate solicit; use std::env; use std::str; use solicit::http::Response; use solicit::http::cl...
else { let port = match str::FromStr::from_str(parts[1]) { Err(_) => { println!("Invalid host (invalid port given)"); print_usage(); return; }, Ok(port) => port, }; (parts[0], port) }; let responses = f...
{ (parts[0], 80) }
conditional_block
client_simple.rs
//! An example of usage of the `solicit::client::SimpleClient` API. //! //! This is a simple implementation of an HTTP/2 client, built on top of the API of `solicit::http` //! that performs all IO in the main thread. extern crate solicit; use std::env; use std::str; use solicit::http::Response; use solicit::http::cl...
println!( "NOTE: The example does not accept URLs, rather the host name and a list of paths"); } let host = env::args().nth(1); let paths: Vec<_> = env::args().skip(2).collect(); if host.is_none() || paths.is_empty() { print_usage(); return; } let host = hos...
} fn main() { fn print_usage() { println!("Usage: client_simple <host>[:<port>] <path> [<path>...]");
random_line_split
client_simple.rs
//! An example of usage of the `solicit::client::SimpleClient` API. //! //! This is a simple implementation of an HTTP/2 client, built on top of the API of `solicit::http` //! that performs all IO in the main thread. extern crate solicit; use std::env; use std::str; use solicit::http::Response; use solicit::http::cl...
let host = env::args().nth(1); let paths: Vec<_> = env::args().skip(2).collect(); if host.is_none() || paths.is_empty() { print_usage(); return; } let host = host.unwrap(); // Split off the port, if present let parts: Vec<_> = host.split(":").collect(); if parts.len() ...
{ println!("Usage: client_simple <host>[:<port>] <path> [<path>...]"); println!( "NOTE: The example does not accept URLs, rather the host name and a list of paths"); }
identifier_body
client_simple.rs
//! An example of usage of the `solicit::client::SimpleClient` API. //! //! This is a simple implementation of an HTTP/2 client, built on top of the API of `solicit::http` //! that performs all IO in the main thread. extern crate solicit; use std::env; use std::str; use solicit::http::Response; use solicit::http::cl...
() { println!("Usage: client_simple <host>[:<port>] <path> [<path>...]"); println!( "NOTE: The example does not accept URLs, rather the host name and a list of paths"); } let host = env::args().nth(1); let paths: Vec<_> = env::args().skip(2).collect(); if host.is_none() || ...
print_usage
identifier_name
option_map_unit_fn_unfixable.rs
#![warn(clippy::option_map_unit_fn)] #![allow(unused)] fn do_nothing<T>(_: T) {} fn diverge<T>(_: T) ->! { panic!() } fn
(value: usize) -> usize { value + 1 } #[rustfmt::skip] fn option_map_unit_fn() { x.field.map(|value| { do_nothing(value); do_nothing(value) }); x.field.map(|value| if value > 0 { do_nothing(value); do_nothing(value) }); // Suggestion for the let block should be `{... }` as it's too difficult to buil...
plus_one
identifier_name
option_map_unit_fn_unfixable.rs
#![warn(clippy::option_map_unit_fn)] #![allow(unused)] fn do_nothing<T>(_: T) {} fn diverge<T>(_: T) ->! { panic!() } fn plus_one(value: usize) -> usize { value + 1 } #[rustfmt::skip] fn option_map_unit_fn() { x.field.map(|value| { do_nothing(value); do_nothing(value) }); x.field.map(|value| if va...
x.field.map(|value| { do_nothing(value); do_nothing(value); }); // The following should suggest `if let Some(_X)...` as it's difficult to generate a proper let variable name for them Some(42).map(diverge); "12".parse::<i32>().ok().map(diverge); Some(plus_one(1)).map(do_nothing); // Should sugg...
// proper suggestion for these cases x.field.map(|value| { do_nothing(value); do_nothing(value) });
random_line_split