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
csssupportsrule.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 cssparser::{Parser, ParserInput}; use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; use dom::bindi...
}
{ let guard = self.cssconditionrule.shared_lock().read(); self.supportsrule .read_with(&guard) .to_css_string(&guard) .into() }
identifier_body
borrowck-borrow-overloaded-auto-deref.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 ...
(x: Rc<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_mut_method2(mut x: Rc<Point>) { x.set(0, 0); //~ ERROR cannot borrow } fn deref_extend_method(x: &Rc<Point>) -> &isize { x.x_ref() } fn deref_extend_mut_method1(x: &Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } fn dere...
deref_mut_method1
identifier_name
borrowck-borrow-overloaded-auto-deref.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn deref(&self) -> &T { unsafe { &*self.value } } } struct Point { x: isize, y: isize } impl Point { fn get(&self) -> (isize, isize) { (self.x, self.y) } fn set(&mut self, x: isize, y: isize) { self.x = x; self.y = y; } fn x_ref(&self) -> &isize { ...
impl<T> Deref for Rc<T> { type Target = T;
random_line_split
borrowck-borrow-overloaded-auto-deref.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn deref_extend_mut_method1(x: &Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } fn deref_extend_mut_method2(x: &mut Rc<Point>) -> &mut isize { x.y_mut() //~ ERROR cannot borrow } fn assign_method1<'a>(x: Rc<Point>) { *x.y_mut() = 3; //~ ERROR cannot borrow } fn assign_method2<'a>(x: &'a ...
{ x.x_ref() }
identifier_body
bytes.rs
// These are tests specifically crafted for regexes that can match arbitrary // bytes. // A silly wrapper to make it possible to write and match raw bytes. struct R<'a>(&'a [u8]); impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } mat!(word_boundary, r"(?-u) \b", " δ", None); #[cfg(feature =...
mat!(perl_d_unicode, r"\d+", "1२३9", Some((0, 8))); mat!(perl_s_ascii, r"(?-u)\s+", " \u{1680}", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(perl_s_unicode, r"\s+", " \u{1680}", Some((0, 4))); // The first `(.+)` matches two Unicode codepoints, but can't match the 5th // byte, which isn't valid UTF-8. The sec...
mat!(perl_w_unicode, r"\w+", "aδ", Some((0, 3))); mat!(perl_d_ascii, r"(?-u)\d+", "1२३9", Some((0, 1))); #[cfg(feature = "unicode-perl")]
random_line_split
bytes.rs
// These are tests specifically crafted for regexes that can match arbitrary // bytes. // A silly wrapper to make it possible to write and match raw bytes. struct R<'a>(&'a [u8]); impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8]
} mat!(word_boundary, r"(?-u) \b", " δ", None); #[cfg(feature = "unicode-perl")] mat!(word_boundary_unicode, r" \b", " δ", Some((0, 1))); mat!(word_not_boundary, r"(?-u) \B", " δ", Some((0, 1))); #[cfg(feature = "unicode-perl")] mat!(word_not_boundary_unicode, r" \B", " δ", None); mat!(perl_w_ascii, r"(?-u)\w+", "aδ...
{ self.0 }
identifier_body
bytes.rs
// These are tests specifically crafted for regexes that can match arbitrary // bytes. // A silly wrapper to make it possible to write and match raw bytes. struct
<'a>(&'a [u8]); impl<'a> R<'a> { fn as_bytes(&self) -> &'a [u8] { self.0 } } mat!(word_boundary, r"(?-u) \b", " δ", None); #[cfg(feature = "unicode-perl")] mat!(word_boundary_unicode, r" \b", " δ", Some((0, 1))); mat!(word_not_boundary, r"(?-u) \B", " δ", Some((0, 1))); #[cfg(feature = "unicode-perl")]...
R
identifier_name
client.rs
//! Defines functionality for a minimalistic synchronous client. use hyper::{Client as HttpClient, Decoder, Encoder, Next}; use hyper::client::{Handler, Request as ClientRequest, Response as ClientResponse}; use hyper::net::HttpStream; use std::thread::{self, Thread}; use buffer::Buffer; pub struct Client { res...
} pub fn status(&self) -> ::hyper::status::StatusCode { *self.result.response.as_ref().unwrap().status() } } struct ClientHandler { thread: Thread, buffer: Buffer, result: *mut RequestResult } unsafe impl Send for ClientHandler {} impl ClientHandler { fn new(result: &mut Request...
{ Vec::new() }
conditional_block
client.rs
//! Defines functionality for a minimalistic synchronous client. use hyper::{Client as HttpClient, Decoder, Encoder, Next}; use hyper::client::{Handler, Request as ClientRequest, Response as ClientResponse}; use hyper::net::HttpStream; use std::thread::{self, Thread}; use buffer::Buffer; pub struct Client { res...
fn on_request(&mut self, _req: &mut ClientRequest) -> Next { Next::read() } fn on_request_writable(&mut self, _encoder: &mut Encoder<HttpStream>) -> Next { Next::read() } fn on_response(&mut self, res: ClientResponse) -> Next { use hyper::header::ContentLength; if ...
} } impl Handler<HttpStream> for ClientHandler {
random_line_split
client.rs
//! Defines functionality for a minimalistic synchronous client. use hyper::{Client as HttpClient, Decoder, Encoder, Next}; use hyper::client::{Handler, Request as ClientRequest, Response as ClientResponse}; use hyper::net::HttpStream; use std::thread::{self, Thread}; use buffer::Buffer; pub struct Client { res...
} impl Handler<HttpStream> for ClientHandler { fn on_request(&mut self, _req: &mut ClientRequest) -> Next { Next::read() } fn on_request_writable(&mut self, _encoder: &mut Encoder<HttpStream>) -> Next { Next::read() } fn on_response(&mut self, res: ClientResponse) -> Next { ...
{ unsafe { (*self.result).body = Some(self.buffer.take()); } // unlocks waiting thread self.thread.unpark(); }
identifier_body
client.rs
//! Defines functionality for a minimalistic synchronous client. use hyper::{Client as HttpClient, Decoder, Encoder, Next}; use hyper::client::{Handler, Request as ClientRequest, Response as ClientResponse}; use hyper::net::HttpStream; use std::thread::{self, Thread}; use buffer::Buffer; pub struct Client { res...
(&mut self, err: ::hyper::Error) -> Next { println!("ERROR: {}", err); Next::remove() } }
on_error
identifier_name
lib.rs
#![allow(dead_code)] extern crate oscillator; extern crate stopwatch; use oscillator::Oscillator; use stopwatch::Stopwatch; fn assert_near(a : f32, b : f32)
#[test] fn test_new() { let mut osc = Oscillator::new(); assert_eq!(osc.get_value(), 1.0); } #[test] fn test_null_freq() { let mut osc = Oscillator::start_new(); osc.set_frequency(0.0); assert_eq!(osc.get_value(), 1.0); } #[test] fn test_cycle() { let mut timer = Stopwatch::start_new(); ...
{ assert!((a-b).abs() < 0.05) }
identifier_body
lib.rs
#![allow(dead_code)] extern crate oscillator; extern crate stopwatch; use oscillator::Oscillator; use stopwatch::Stopwatch; fn assert_near(a : f32, b : f32) { assert!((a-b).abs() < 0.05) } #[test] fn test_new() { let mut osc = Oscillator::new(); assert_eq!(osc.get_value(), 1.0); } #[test] fn test_null_...
#[test] fn test_cycle() { let mut timer = Stopwatch::start_new(); let mut osc = Oscillator::start_new(); assert_near(osc.get_value(), 1.0); while timer.elapsed_ms() < 500 { } assert_near(osc.get_value(), 0.0); while timer.elapsed_ms() < 1000 { } assert_near(osc.get_value(), 1.0); } #[t...
random_line_split
lib.rs
#![allow(dead_code)] extern crate oscillator; extern crate stopwatch; use oscillator::Oscillator; use stopwatch::Stopwatch; fn assert_near(a : f32, b : f32) { assert!((a-b).abs() < 0.05) } #[test] fn test_new() { let mut osc = Oscillator::new(); assert_eq!(osc.get_value(), 1.0); } #[test] fn test_null_...
() { let mut timer = Stopwatch::start_new(); let mut osc = Oscillator::start_new(); assert_near(osc.get_value(), 1.0); while timer.elapsed_ms() < 500 { } assert_near(osc.get_value(), 0.0); while timer.elapsed_ms() < 1000 { } assert_near(osc.get_value(), 1.0); } #[test] fn test_freq() {...
test_cycle
identifier_name
build.rs
use std::env; fn main() { println!("cargo:rerun-if-changed=build.rs"); let target = env::var("TARGET").expect("TARGET was not set");
if env::var("RUST_STD_FREEBSD_12_ABI").is_ok() { println!("cargo:rustc-cfg=freebsd12"); } } else if target.contains("linux") || target.contains("netbsd") || target.contains("dragonfly") || target.contains("openbsd") || target.contains("solaris") ||...
if target.contains("freebsd") {
random_line_split
build.rs
use std::env; fn main() { println!("cargo:rerun-if-changed=build.rs"); let target = env::var("TARGET").expect("TARGET was not set"); if target.contains("freebsd") { if env::var("RUST_STD_FREEBSD_12_ABI").is_ok() { println!("cargo:rustc-cfg=freebsd12"); } } else if target.con...
else { // This is for Cargo's build-std support, to mark std as unstable for // typically no_std platforms. // This covers: // - os=none ("bare metal" targets) // - mipsel-sony-psp // - nvptx64-nvidia-cuda // - arch=avr // - tvos (aarch64-apple-tvos, x86_...
{ // These platforms don't have any special requirements. }
conditional_block
build.rs
use std::env; fn
() { println!("cargo:rerun-if-changed=build.rs"); let target = env::var("TARGET").expect("TARGET was not set"); if target.contains("freebsd") { if env::var("RUST_STD_FREEBSD_12_ABI").is_ok() { println!("cargo:rustc-cfg=freebsd12"); } } else if target.contains("linux") ...
main
identifier_name
build.rs
use std::env; fn main()
|| target.contains("l4re") || target.contains("redox") || target.contains("haiku") || target.contains("vxworks") || target.contains("wasm32") || target.contains("wasm64") || target.contains("asmjs") || target.contains("espidf") || target.contains("...
{ println!("cargo:rerun-if-changed=build.rs"); let target = env::var("TARGET").expect("TARGET was not set"); if target.contains("freebsd") { if env::var("RUST_STD_FREEBSD_12_ABI").is_ok() { println!("cargo:rustc-cfg=freebsd12"); } } else if target.contains("linux") ||...
identifier_body
issue-9906.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 ...
(){ 1+1; } }
foo
identifier_name
issue-9906.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
// except according to those terms. // xfail-fast windows doesn't like extern mod // aux-build:issue-9906.rs pub use other::FooBar; pub use other::foo; mod other { pub struct FooBar{value: int} impl FooBar{ pub fn new(val: int) -> FooBar { FooBar{value: val} } } pub fn fo...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
result.rs
use std::error::Error; use std::fmt; use std::fmt::Display; use std::ptr; use env::NapiEnv; use sys::{napi_create_error, napi_create_range_error, napi_create_type_error, napi_status, napi_value}; use value::{NapiString, NapiValue}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum
{ InvalidArg, ObjectExpected, StringExpected, NameExpected, FunctionExpected, NumberExpected, BooleanExpected, ArrayExpected, GenericFailure, PendingException, Cancelled, EscapeCalledTwice, ApplicationError, } #[derive(Clone, Debug)] pub struct NapiError { pub k...
NapiErrorKind
identifier_name
result.rs
use std::error::Error; use std::fmt; use std::fmt::Display; use std::ptr; use env::NapiEnv; use sys::{napi_create_error, napi_create_range_error, napi_create_type_error, napi_status, napi_value}; use value::{NapiString, NapiValue}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NapiErrorKind { In...
NapiErrorKind::EscapeCalledTwice => { "NapiError: escape called twice" } NapiErrorKind::ApplicationError => "NapiError: application error", } } } impl Display for NapiError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write...
NapiErrorKind::PendingException => "NapiError: pending exception", NapiErrorKind::Cancelled => "NapiError: cancelled",
random_line_split
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mps...
(self, c: Customer) { println!("Barber {:?} is cutting hair of customer {:?}.", self.id, c.id); thread::sleep_ms(c.hair_length); self.to_shop.clone().send(Message::BarberFree(self)).unwrap(); } } impl Barbershop { fn new(num_chairs: usize) -> Barbershop { let (tx, rx) = mpsc::ch...
cut_hair
identifier_name
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mps...
fn hire_barber(&mut self, id: i32) { let b = Barber::new(id, self); self.barber_free(b); } fn serve_customer(&mut self) { if self.free_barbers.len() == 0 { return; } if self.waiting_customers.len() == 0 { return; } ...
{ let (tx, rx) = mpsc::channel::<Message>(); Barbershop{ tx: tx, rx: rx, num_chairs: num_chairs, waiting_customers: VecDeque::<Customer>::new(), free_barbers: VecDeque::<Barber>::new(), } }
identifier_body
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mps...
let b = self.free_barbers.pop_front().unwrap(); let c = self.waiting_customers.pop_front().unwrap(); thread::spawn(move || b.cut_hair(c)); } fn barber_free(&mut self, b: Barber) { self.free_barbers.push_back(b); self.serve_customer(); } fn new_customer(&mut s...
{ return; }
conditional_block
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mps...
} thread::sleep_ms(10000); }
hair_length: hair_lengths.ind_sample(&mut rng), }; println!("Customer {:?} arrives at shop.", i); to_shop.send(Message::CustomerArrives(c)).unwrap(); thread::sleep_ms(customer_interval.ind_sample(&mut rng));
random_line_split
trace_faulty_macros.rs
// compile-flags: -Z trace-macros #![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { my_faulty_macro!(bcd); //~ ERROR no rules }; } macro_rules! pat_macro { () => { pat_macro!(A{a:a, b:0, c:_,..}); }; ($a:pat) => { $a //~ ERROR expected expression }; } m...
() {} #[derive(Debug)] //~ ERROR `derive` may only be applied to `struct`s fn use_derive_macro_as_attr() {}
use_bang_macro_as_attr
identifier_name
trace_faulty_macros.rs
// compile-flags: -Z trace-macros #![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { my_faulty_macro!(bcd); //~ ERROR no rules }; } macro_rules! pat_macro { () => { pat_macro!(A{a:a, b:0, c:_,..}); }; ($a:pat) => { $a //~ ERROR expected expression }; } m...
#[my_macro] fn use_bang_macro_as_attr() {} #[derive(Debug)] //~ ERROR `derive` may only be applied to `struct`s fn use_derive_macro_as_attr() {}
random_line_split
trace_faulty_macros.rs
// compile-flags: -Z trace-macros #![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { my_faulty_macro!(bcd); //~ ERROR no rules }; } macro_rules! pat_macro { () => { pat_macro!(A{a:a, b:0, c:_,..}); }; ($a:pat) => { $a //~ ERROR expected expression }; } m...
#[my_macro] fn use_bang_macro_as_attr() {} #[derive(Debug)] //~ ERROR `derive` may only be applied to `struct`s fn use_derive_macro_as_attr() {}
{ my_faulty_macro!(); my_recursive_macro!(); test!(); non_exisiting!(); derive!(Debug); let a = pat_macro!(); }
identifier_body
nested-matchs.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() { foo(); }
{ match Some::<int>(5) { Some::<int>(_x) => { let mut bar; match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } } println!("{:?}", bar); } None::<int> => { println!("hello"); } }
identifier_body
nested-matchs.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 ...
} None::<int> => { println!("hello"); } } } pub fn main() { foo(); }
random_line_split
nested-matchs.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 ...
() ->! { fail!(); } fn foo() { match Some::<int>(5) { Some::<int>(_x) => { let mut bar; match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } } println!("{:?}", bar); } None::<int> => { println!("hello"); } } } pub fn main() { foo(); }
baz
identifier_name
native.rs
use crate::{Backend, RawDevice, ROUGH_MAX_ATTACHMENT_COUNT}; use ash::{version::DeviceV1_0, vk}; use hal::{ device::OutOfMemory, image::{Extent, SubresourceRange}, pso, }; use inplace_it::inplace_or_alloc_from_iter; use parking_lot::Mutex; use smallvec::SmallVec; use std::{collections::HashMap, sync::Arc}; ...
#[derive(Debug, Hash, PartialEq, Eq)] pub struct ImageView { pub(crate) image: vk::Image, pub(crate) raw: vk::ImageView, pub(crate) range: SubresourceRange, } #[derive(Debug, Hash)] pub struct Sampler(pub vk::Sampler); #[derive(Debug, Hash)] pub struct RenderPass { pub raw: vk::RenderPass, pub att...
pub(crate) ty: vk::ImageType, pub(crate) flags: vk::ImageCreateFlags, pub(crate) extent: vk::Extent3D, }
random_line_split
native.rs
use crate::{Backend, RawDevice, ROUGH_MAX_ATTACHMENT_COUNT}; use ash::{version::DeviceV1_0, vk}; use hal::{ device::OutOfMemory, image::{Extent, SubresourceRange}, pso, }; use inplace_it::inplace_or_alloc_from_iter; use parking_lot::Mutex; use smallvec::SmallVec; use std::{collections::HashMap, sync::Arc}; ...
(raw: vk::DescriptorPool, device: &Arc<RawDevice>) -> Self { DescriptorPool { raw, device: Arc::clone(device), temp_raw_sets: Vec::new(), temp_raw_layouts: Vec::new(), temp_layout_bindings: Vec::new(), } } pub(crate) fn finish(self) ->...
new
identifier_name
native.rs
use crate::{Backend, RawDevice, ROUGH_MAX_ATTACHMENT_COUNT}; use ash::{version::DeviceV1_0, vk}; use hal::{ device::OutOfMemory, image::{Extent, SubresourceRange}, pso, }; use inplace_it::inplace_or_alloc_from_iter; use parking_lot::Mutex; use smallvec::SmallVec; use std::{collections::HashMap, sync::Arc}; ...
}) } unsafe fn reset(&mut self) { assert_eq!( Ok(()), self.device .raw .reset_descriptor_pool(self.raw, vk::DescriptorPoolResetFlags::empty()) ); } } #[derive(Debug, Hash)] pub struct QueryPool(pub vk::QueryPool);
{ if let Err(e) = self.device.raw.free_descriptor_sets(self.raw, sets) { error!("free_descriptor_sets error {}", e); } }
conditional_block
audio.rs
().unwrap(); //! //! let desired_spec = AudioSpecDesired { //! freq: Some(44100), //! channels: Some(1), // mono //! samples: None // default sample size //! }; //! //! let device = audio_subsystem.open_playback(None, &desired_spec, |spec| { //! // initialize the audio callback //! SquareWave...
(n: u64) -> Option<AudioStatus> { FromPrimitive::from_i64(n as i64) } } #[derive(Copy, Clone)] pub struct DriverIterator { length: i32, index: i32 } impl Iterator for DriverIterator { type Item = &'static str; #[inline] fn next(&mut self) -> Option<&'static str> { if self.index >= self.le...
from_u64
identifier_name
audio.rs
audio().unwrap(); //! //! let desired_spec = AudioSpecDesired { //! freq: Some(44100), //! channels: Some(1), // mono //! samples: None // default sample size //! }; //! //! let device = audio_subsystem.open_playback(None, &desired_spec, |spec| { //! // initialize the audio callback //! Squar...
impl ExactSizeIterator for DriverIterator { } /// Gets an iterator of all audio drivers compiled into the SDL2 library. #[inline] pub fn drivers() -> DriverIterator { // This function is thread-safe and doesn't require the audio subsystem to be initialized. // The list of drivers are read-only and statically c...
let l = self.length as usize; (l, Some(l)) } }
random_line_split
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. /*! `Worker` provides a mechanism to run tasks asynchronously (i.e. in the background) with some additional features, for example, ticks. A worker contains: - A runner (which should implement the `Runnable` trait): to run tasks one by one or in batc...
worker.stop(); drop(rx); } }
let (tx, rx) = mpsc::channel(); lazy_worker.start(BatchRunner { ch: tx }); assert!(rx.recv_timeout(Duration::from_secs(3)).is_ok());
random_line_split
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. /*! `Worker` provides a mechanism to run tasks asynchronously (i.e. in the background) with some additional features, for example, ticks. A worker contains: - A runner (which should implement the `Runnable` trait): to run tasks one by one or in batc...
() { let worker = Builder::new("test-worker-busy") .pending_capacity(3) .create(); let mut lazy_worker = worker.lazy_build("test-busy"); let scheduler = lazy_worker.scheduler(); for i in 0..3 { scheduler.schedule(i).unwrap(); } assert_eq...
test_pending_capacity
identifier_name
health.rs
use futures::future::ok; use http::FutureHandled; use http::ServerResponse; use hyper; use hyper::Request; use hyper::Response; use hyper::server::NewService; use hyper::server::Service; use std::io; /// `/health` service returning OK status if microservice is running (obviously) #[derive(Debug, Copy, Clone)] pub stru...
type Response = Response; type Error = hyper::Error; type Future = FutureHandled; fn call(&self, _req: Request) -> Self::Future { box ok(ServerResponse::Data(HealthStatus::ok()).into()) } } #[derive(Debug, Copy, Clone, Serialize)] struct HealthStatus { status: &'static str, } impl Heal...
random_line_split
health.rs
use futures::future::ok; use http::FutureHandled; use http::ServerResponse; use hyper; use hyper::Request; use hyper::Response; use hyper::server::NewService; use hyper::server::Service; use std::io; /// `/health` service returning OK status if microservice is running (obviously) #[derive(Debug, Copy, Clone)] pub stru...
}
{ HealthStatus { status: "OK" } }
identifier_body
health.rs
use futures::future::ok; use http::FutureHandled; use http::ServerResponse; use hyper; use hyper::Request; use hyper::Response; use hyper::server::NewService; use hyper::server::Service; use std::io; /// `/health` service returning OK status if microservice is running (obviously) #[derive(Debug, Copy, Clone)] pub stru...
{ status: &'static str, } impl HealthStatus { fn ok() -> Self { HealthStatus { status: "OK" } } }
HealthStatus
identifier_name
borrowck-uniq-via-lend.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 ...
() { struct F { f: G } struct G { g: H } struct H { h: ~int } let mut v = F {f: G {g: H {h: ~3}}}; borrow(v.f.g.h); } fn aliased_imm() { let mut v = ~3; let _w = &v; borrow(v); } fn aliased_const() { let mut v = ~3; let _w = &const v; borrow(v); } fn aliased_mut() { le...
local_recs
identifier_name
borrowck-uniq-via-lend.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 ...
fn local_rec() { struct F { f: ~int } let mut v = F {f: ~3}; borrow(v.f); } fn local_recs() { struct F { f: G } struct G { g: H } struct H { h: ~int } let mut v = F {f: G {g: H {h: ~3}}}; borrow(v.f.g.h); } fn aliased_imm() { let mut v = ~3; let _w = &v; borrow(v); } fn al...
random_line_split
main.rs
extern crate serial; extern crate num_cpus; use std::io; use std::io::{Read, BufReader, BufRead, Write}; use std::fs::File; use std::str::FromStr; use std::thread::sleep; use std::time::Duration; use std::num::ParseFloatError; use std::collections::VecDeque; use serial::prelude::*; use serial::SerialDevice; #[derive...
let cpus = s.cpus as f64; let di = (s.uptimes.back().unwrap().idle - s.uptimes.front().unwrap().idle) / cpus; return Ok(1.0 - (di / du)); } fn scale(v: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> u8 { let mut f = (v - old_min) * (new_max - new_min) / (old_max - old_min) + new_min...
{ return Ok(0.0); }
conditional_block
main.rs
extern crate serial; extern crate num_cpus; use std::io; use std::io::{Read, BufReader, BufRead, Write}; use std::fs::File; use std::str::FromStr; use std::thread::sleep; use std::time::Duration; use std::num::ParseFloatError; use std::collections::VecDeque; use serial::prelude::*; use serial::SerialDevice; #[derive...
return Some(*state); } Some(*state) }) .filter_map(|state| { let (total_option, avail_option) = state; if let Some(total) = total_option { if let Some(avail) = avail_option { return Some((total, avail)); ...
state.1 = Some(val.parse::<f64>().unwrap_or(0.0));
random_line_split
main.rs
extern crate serial; extern crate num_cpus; use std::io; use std::io::{Read, BufReader, BufRead, Write}; use std::fs::File; use std::str::FromStr; use std::thread::sleep; use std::time::Duration; use std::num::ParseFloatError; use std::collections::VecDeque; use serial::prelude::*; use serial::SerialDevice; #[derive...
fn scale(v: f64, old_min: f64, old_max: f64, new_min: f64, new_max: f64) -> u8 { let mut f = (v - old_min) * (new_max - new_min) / (old_max - old_min) + new_min; f = f.min(new_max).max(new_min); f as u8 } fn send_info(port: &mut serial::SystemPort, cpu_used: f64, mem_used: f64) -> serial::Result<()> { ...
{ let last_uptime = uptime()?; if s.uptimes.len() > WINDOW { s.uptimes.pop_front(); } s.uptimes.push_back(last_uptime); let du = s.uptimes.back().unwrap().uptime - s.uptimes.front().unwrap().uptime; if du < 0.001 { return Ok(0.0); } let cpus = s.cpus as f64; let di...
identifier_body
main.rs
extern crate serial; extern crate num_cpus; use std::io; use std::io::{Read, BufReader, BufRead, Write}; use std::fs::File; use std::str::FromStr; use std::thread::sleep; use std::time::Duration; use std::num::ParseFloatError; use std::collections::VecDeque; use serial::prelude::*; use serial::SerialDevice; #[derive...
() { let mut port = open_serial_port().unwrap(); let mut cm = init_cpu_measurement().unwrap(); let delay = Duration::from_millis(100); loop { sleep(delay); let cpu_usage = cpu_usage(&mut cm).unwrap(); let mem_usage = get_mem_usage().unwrap(); send_info(&mut port, cpu_usa...
main
identifier_name
quality.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/. */ //TODO(eijebong): Remove this once typed headers figure out quality // This is copy pasted from the old hyper hea...
(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.item, fmt)?; match self.quality.0 { 1000 => Ok(()), 0 => fmt.write_str("; q=0"), mut x => { fmt.write_str("; q=0.")?; let mut digits = *b"000"; d...
fmt
identifier_name
quality.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/. */ //TODO(eijebong): Remove this once typed headers figure out quality // This is copy pasted from the old hyper hea...
{ HeaderValue::from_str( &q.iter() .map(|q| q.to_string()) .collect::<Vec<String>>() .join(", "), ) .unwrap() }
identifier_body
quality.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/. */ //TODO(eijebong): Remove this once typed headers figure out quality // This is copy pasted from the old hyper hea...
x /= 10; digits[1] = (x % 10) as u8 + b'0'; x /= 10; digits[0] = (x % 10) as u8 + b'0'; let s = str::from_utf8(&digits[..]).unwrap(); fmt.write_str(s.trim_right_matches('0')) }, } } } pub fn quality...
fmt.write_str("; q=0.")?; let mut digits = *b"000"; digits[2] = (x % 10) as u8 + b'0';
random_line_split
issue-19367.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 ...
() { let mut a = (0, Some("right".to_string())); let b = match a.1 { Some(v) => { a.1 = Some("wrong".to_string()); v } None => String::new() }; println!("{}", b); assert_eq!(b, "right"); let mut s = S{ o: Some("right".to_string()) }; let b = ...
main
identifier_name
issue-19367.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { let mut a = (0, Some("right".to_string())); let b = match a.1 { Some(v) => { a.1 = Some("wrong".to_string()); v } None => String::new() }; println!("{}", b); assert_eq!(b, "right"); let mut s = S{ o: Some("right".to_string()) }; ...
// Make sure we don't reuse the same alloca when matching // on field of struct or tuple which we reassign in the match body.
random_line_split
revisions_test.rs
extern crate gitters; use gitters::objects; use gitters::revisions; #[test] fn full_sha1_resolves_to_self() { assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21")); } #[test] fn partial_sha1_resolves_...
() { assert_eq!( Ok(objects::Name("3e6a5d72d0ce0af8402c7d467d1b754b61b79d16".to_string())), revisions::resolve("d7698dd~3")); } #[test] fn branch_resolves_to_sha1() { assert_eq!( Ok(objects::Name("41cf28e8cac50f5cfeda40cfbfdd049763541c5a".to_string())), revisions::resolve("intro...
ancestor_specification_resolves_to_ancestor_sha1
identifier_name
revisions_test.rs
extern crate gitters; use gitters::objects; use gitters::revisions; #[test] fn full_sha1_resolves_to_self() { assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21")); } #[test] fn partial_sha1_resolves_...
#[test] fn invalid_revision_does_not_resolve() { assert_eq!( Err(revisions::Error::InvalidRevision), revisions::resolve("invalid")); }
{ assert_eq!( Ok(objects::Name("41cf28e8cac50f5cfeda40cfbfdd049763541c5a".to_string())), revisions::resolve("introduce-tests")); }
identifier_body
revisions_test.rs
extern crate gitters; use gitters::objects; use gitters::revisions; #[test] fn full_sha1_resolves_to_self() {
} #[test] fn partial_sha1_resolves_to_full_sha1_if_unambiguous() { assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025e")); } #[test] fn multiple_parent_specification_resolves_to_ancestor_sha1() { assert_eq!( Ok(objects::N...
assert_eq!( Ok(objects::Name("4ddb0025ef5914b51fb835495f5259a6d962df21".to_string())), revisions::resolve("4ddb0025ef5914b51fb835495f5259a6d962df21"));
random_line_split
display_controller.rs
use std::thread; use std::sync::{mpsc, Arc, Mutex}; use rustc_serialize::json; use input_parser; use channel::Channel; use current_state::{self, CurrentState}; use rdispatcher::{Subscribe, SubscribeHandle, DispatchMessage, Broadcast, BroadcastHandle}; use dispatch_type::DispatchType; use view::View; use view_data::Vie...
(payload: &str, state: &CurrentState, current_view_data: &mut ViewData, all_view_data: &mut Vec<ViewData>) { let channel_names = state.channel_names(); current_view_data.add_debug(format!("Channels: {}", channel_names.connect(", "))); } fn handle_user_input(payload: &str, state: &CurrentState, current_view_data:...
handle_list_channels
identifier_name
display_controller.rs
use std::thread; use std::sync::{mpsc, Arc, Mutex}; use rustc_serialize::json; use input_parser; use channel::Channel; use current_state::{self, CurrentState}; use rdispatcher::{Subscribe, SubscribeHandle, DispatchMessage, Broadcast, BroadcastHandle}; use dispatch_type::DispatchType; use view::View; use view_data::Vie...
fn broadcast_handle(&mut self) -> BroadcastHandle<DispatchType> { let (tx, rx) = mpsc::channel::<DispatchMessage<DispatchType>>(); self.broadcast_tx = Some(tx); rx } }
} impl Broadcast<DispatchType> for DisplayController {
random_line_split
workqueue.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 work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with ...
} Data(work) => { work_unit = work; back_off_sleep = 0 as u32; break } } ...
random_line_split
workqueue.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 work queue for scheduling units of work across threads in a fork-join fashion. //! //! Data associated with ...
<QueueData:'static, WorkData:'static> { /// The communication channel to the workers. chan: Sender<WorkerMsg<QueueData, WorkData>>, /// The worker end of the deque, if we have it. deque: Option<Worker<WorkUnit<QueueData, WorkData>>>, /// The thief end of the work-stealing deque. thief: Stealer<W...
WorkerInfo
identifier_name
blinky.rs
//! Turns the user LED on #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::Timer; use blue_pill::led::{self, Green}; use b...
// IDLE LOOP fn idle(_prio: P0, _thr: T0) ->! { // Sleep loop { rtfm::wfi(); } } // TASKS tasks!(stm32f103xx, { blink: Task { interrupt: TIM1_UP_TIM10, priority: P1, enabled: true, }, }); fn blink(mut task: TIM1_UP_TIM10, ref prio: P1, ref thr: T1) { static ST...
{ let gpioc = &GPIOC.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); led::init(gpioc, rcc); timer.init(FREQUENCY.invert(), rcc); timer.resume(); }
identifier_body
blinky.rs
//! Turns the user LED on #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::Timer; use blue_pill::led::{self, Green}; use b...
} else { Green.off(); } }
random_line_split
blinky.rs
//! Turns the user LED on #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::Timer; use blue_pill::led::{self, Green}; use b...
(mut task: TIM1_UP_TIM10, ref prio: P1, ref thr: T1) { static STATE: Local<bool, TIM1_UP_TIM10> = Local::new(false); let tim1 = TIM1.access(prio, thr); let timer = Timer(&*tim1); // NOTE(wait) timeout should have already occurred timer.wait().unwrap(); let state = STATE.borrow_mut(&mut task)...
blink
identifier_name
blinky.rs
//! Turns the user LED on #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; use blue_pill::Timer; use blue_pill::led::{self, Green}; use b...
else { Green.off(); } }
{ Green.on(); }
conditional_block
size_hint.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::I...
} impl FnMut<Args> for F { extern "rust-call" fn call_mut(&mut self, (item,): Args) -> Self::Output { A { begin: 0, end: item } } } #[test] fn size_hint_test1() { let a: A<T> = A { begin: 0, end: 10 }; let f: F = F; let mut flat_map: FlatMap<A<T>, U, F> = a.flat_map::<U, F>(f); for n ...
{ A { begin: 0, end: item } }
identifier_body
size_hint.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::I...
for i in 0..n { let x: Option<<U as IntoIterator>::Item> = flat_map.next(); match x { Some(v) => { assert_eq!(v, i); } None => { assert!(false); } } let (lower, _): (usize, Option<usize>) = flat_map.size_hint(); assert_eq!(lower, (n - i - 1) as usize); } } assert_eq!(flat_map.next(),...
random_line_split
size_hint.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct
<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::Item> { if self.begin < self.end { let result = self.begin; self.begin = self.begin.wrapping_add(1); Some::<Self::Item>(result) } els...
A
identifier_name
size_hint.rs
#![feature(core, unboxed_closures)] extern crate core; #[cfg(test)] mod tests { use core::iter::Iterator; use core::iter::FlatMap; struct A<T> { begin: T, end: T } macro_rules! Iterator_impl { ($T:ty) => { impl Iterator for A<$T> { type Item = $T; fn next(&mut self) -> Option<Self::I...
} let (lower, _): (usize, Option<usize>) = flat_map.size_hint(); assert_eq!(lower, (n - i - 1) as usize); } } assert_eq!(flat_map.next(), None::<Item>); } }
{ assert!(false); }
conditional_block
num.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, x: u8) -> u8 { match x { x @ 0... 9 => b'0' + x, x if x < self.base() => b'a' + (x - 10), x => panic!("number not in the range 0..{}: {}", self.base() - 1, x), } } } /// A helper type for formatting radixes. #[unstable(feature = "core", reason...
digit
identifier_name
num.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 ...
} /// A helper type for formatting radixes. #[unstable(feature = "core", reason = "may be renamed or move to a different module")] #[derive(Copy)] pub struct RadixFmt<T, R>(T, R); /// Constructs a radix formatter in the range of `2..36`. /// /// # Examples /// /// ``` /// use std::fmt::radix; /// assert_e...
{ match x { x @ 0 ... 9 => b'0' + x, x if x < self.base() => b'a' + (x - 10), x => panic!("number not in the range 0..{}: {}", self.base() - 1, x), } }
identifier_body
num.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 ...
} } } } } radix! { Binary, 2, "0b", x @ 0... 2 => b'0' + x } radix! { Octal, 8, "0o", x @ 0... 7 => b'0' + x } radix! { Decimal, 10, "", x @ 0... 9 => b'0' + x } radix! { LowerHex, 16, "0x", x @ 0... 9 => b'0' + x, x @ 10... 15 => b...
fn prefix(&self) -> &'static str { $prefix } fn digit(&self, x: u8) -> u8 { match x { $($x => $conv,)+ x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
random_line_split
num.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 ...
else { // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = zero - (x % base); // Get the current place value. x = x / base; // Deaccumulate the number. ...
{ // Accumulate each digit of the number from the least significant // to the most significant figure. for byte in buf.iter_mut().rev() { let n = x % base; // Get the current place value. x = x / base; ...
conditional_block
benchmark.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! This benchmark generates linear stack with specified parameters, and then //! measures how log it takes to convert it from Bonsai to Hg...
.long(ARG_STACK_SIZE) .takes_value(true) .value_name(ARG_STACK_SIZE) .help("Size of the generated stack"), ) .arg( Arg::with_name(ARG_BLOBSTORE_PUT_MEAN_SECS) .long(ARG_BLOBSTORE_PUT_MEAN_SECS) .takes_va...
{ let matches = args::MononokeAppBuilder::new("mononoke benchmark") .without_arg_types(vec![ ArgType::Config, ArgType::Repo, ArgType::Tunables, ArgType::Runtime, // we construct our own runtime, so these args would do nothing ]) .with_advanced_...
identifier_body
benchmark.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! This benchmark generates linear stack with specified parameters, and then //! measures how log it takes to convert it from Bonsai to Hg...
( ctx: CoreContext, repo: BlobRepo, rng_seed: u64, stack_size: usize, derived_data_type: &str, use_backfill_mode: bool, ) -> Result<(), Error> { println!("rng seed: {}", rng_seed); let mut rng = XorShiftRng::seed_from_u64(rng_seed); // reproducable Rng let mut gen = GenManifest::new...
run
identifier_name
benchmark.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ //! This benchmark generates linear stack with specified parameters, and then //! measures how log it takes to convert it from Bonsai to Hg...
let mut gen = GenManifest::new(); let settings = Default::default(); let (stats, csidq) = gen .gen_stack( ctx.clone(), repo.clone(), &mut rng, &settings, None, std::iter::repeat(16).take(stack_size), ) .timed() ...
println!("rng seed: {}", rng_seed); let mut rng = XorShiftRng::seed_from_u64(rng_seed); // reproducable Rng
random_line_split
fn-simple.rs
// rustfmt-normalize_comments: true fn simple(/*pre-comment on a function!?*/ i: i32/*yes, it's possible! */ ,response: NoWay /* hose */) { fn op(x: Typ, key : &[u8], upd : Box<Fn(Option<&memcache::Item>) -> (memcache::Status, Result<memcache::Item, Option<String>>)>) -> MapR...
<T>(arg: T) -> &SomeType where T: Fn(// First arg A, // Second argument B, C, D, /* pre comment */ E /* last comment */) -> &SomeType { arg(a, b, c, d, e) } fn foo() -> ! {} pub fn http_fetch_async(listener:Box< AsyncCORSResponseListener+Send >, script_chan: Box<ScriptChan+Send...
generic
identifier_name
fn-simple.rs
// rustfmt-normalize_comments: true fn simple(/*pre-comment on a function!?*/ i: i32/*yes, it's possible! */ ,response: NoWay /* hose */) { fn op(x: Typ, key : &[u8], upd : Box<Fn(Option<&memcache::Item>) -> (memcache::Status, Result<memcache::Item, Option<String>>)>) -> MapR...
// #2003 mod foo { fn __bindgen_test_layout_i_open0_c_open1_char_a_open2_char_close2_close1_close0_instantiation() { foo(); } }
formatted_comment = rewrite_comment(comment, block_style, width, offset, formatting_fig); } } }
random_line_split
fn-simple.rs
// rustfmt-normalize_comments: true fn simple(/*pre-comment on a function!?*/ i: i32/*yes, it's possible! */ ,response: NoWay /* hose */) { fn op(x: Typ, key : &[u8], upd : Box<Fn(Option<&memcache::Item>) -> (memcache::Status, Result<memcache::Item, Option<String>>)>) -> MapR...
pub fn http_fetch_async(listener:Box< AsyncCORSResponseListener+Send >, script_chan: Box<ScriptChan+Send>) { } fn some_func<T:Box<Trait+Bound>>(val:T){} fn zzzzzzzzzzzzzzzzzzzz<Type, NodeType> (selff: Type, mut handle: node::Handle<IdRef<'id, Node<K, V>>, Type, NodeType>) ...
{}
identifier_body
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #[cfg(target_os = "android")] extern crate android_injected_glue; #[cfg(target_os = "android")] extern crate andro...
// If not Android, expose the C-API #[cfg(not(target_os = "android"))] mod capi; #[cfg(not(target_os = "android"))] pub use capi::*; // If Android, expose the JNI-API #[cfg(target_os = "android")] mod jniapi; #[cfg(target_os = "android")] pub use jniapi::*;
mod gl_glue;
random_line_split
media_queries.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/. */ //! Servo's media-query device and expression representation. use app_units::Au; use context::QuirksMode; use css...
, } } } } } impl ToCss for Expression { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let (s, l) = match self.0 { ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l), ExpressionKind::...
{ value == *width }
conditional_block
media_queries.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/. */ //! Servo's media-query device and expression representation. use app_units::Au; use context::QuirksMode; use css...
"width" => { ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?)) }, _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))) })) }) } /// Evaluate t...
ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?)) },
random_line_split
media_queries.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/. */ //! Servo's media-query device and expression representation. use app_units::Au; use context::QuirksMode; use css...
/// Take into account a viewport rule taken from the stylesheets. pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) { self.viewport_size = constraints.size; } /// Return the media type of the current device. pub fn media_type(&self) -> MediaType { self...
{ self.device_pixel_ratio }
identifier_body
media_queries.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/. */ //! Servo's media-query device and expression representation. use app_units::Au; use context::QuirksMode; use css...
(&self, _color: RGBA) { // Servo doesn't implement this quirk (yet) } /// Whether a given animation name may be referenced from style. pub fn animation_name_may_be_referenced(&self, _: &KeyframesName) -> bool { // Assume it is, since we don't have any good way to prove it's not. tru...
set_body_text_color
identifier_name
domstringmap.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/. */ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DO...
// https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem fn NamedGetter(&self, name: DOMString) -> Option<DOMString> { self.element.get_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names fn SupportedPropertyNames...
{ self.element.set_custom_attr(name, value) }
identifier_body
domstringmap.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/. */ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DO...
.cloned() .collect() } }
fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.element .supported_prop_names_custom_attr() .iter()
random_line_split
domstringmap.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/. */ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DO...
(element: &HTMLElement) -> DomRoot<DOMStringMap> { let window = window_from_node(element); reflect_dom_object( Box::new(DOMStringMap::new_inherited(element)), &*window, DOMStringMapBinding::Wrap, ) } } // https://html.spec.whatwg.org/multipage/#domstringm...
new
identifier_name
tostr.rs
// This Source Code Form is subject to the terms of the GNU General Public // License, version 3. If a copy of the GPL was not distributed with this file, // You can obtain one at https://www.gnu.org/licenses/gpl.txt. use crate::{ bif::NativeFunc, path::ConcretePath, tree::Tree, value::{Value, ValueData...
; impl NativeFunc for ToStr { fn compute(&self, value: Value, tree: &Tree) -> Fallible<Value> { Ok(Value::from_string(match value.data { ValueData::String(s) => s, ValueData::Integer(i) => format!("{}", i), ValueData::Float(f) => format!("{}", f), ValueData::...
ToStr
identifier_name
tostr.rs
// This Source Code Form is subject to the terms of the GNU General Public // License, version 3. If a copy of the GPL was not distributed with this file, // You can obtain one at https://www.gnu.org/licenses/gpl.txt. use crate::{ bif::NativeFunc, path::ConcretePath, tree::Tree, value::{Value, ValueData...
} fn find_all_possible_inputs( &self, _value_type: (), _tree: &Tree, _out: &mut Vec<ConcretePath>, ) -> Fallible<()> { Ok(()) } fn box_clone(&self) -> Box<dyn NativeFunc + Send + Sync> { Box::new((*self).clone()) } }
}))
random_line_split
ip.rs
// STD Dependencies ----------------------------------------------------------- use std::io::Read; // External Dependencies ------------------------------------------------------ use hyper::Client; use hyper::header::Connection; // Internal Dependencies ------------------------------------------------------ use ::c...
(&self, command: Command) -> ActionGroup { MessageActions::Send::private( &command.message, "Usage: `!ip`".to_string() ) } } // Helpers -------------------------------------------------------------------- fn resolve_ip() -> Result<String, String> { let client = Client...
usage
identifier_name
ip.rs
// STD Dependencies ----------------------------------------------------------- use std::io::Read; // External Dependencies ------------------------------------------------------ use hyper::Client; use hyper::header::Connection; // Internal Dependencies ------------------------------------------------------ use ::c...
fn help(&self) -> &str { "Post the bot's current IP address onto the channel." } fn usage(&self, command: Command) -> ActionGroup { MessageActions::Send::private( &command.message, "Usage: `!ip`".to_string() ) } } // Helpers -------------------------...
{ let response = match resolve_ip() { Ok(ip) => format!( "{} has requested my public IP address which is: {}.", command.member.nickname, ip ), Err(_) => "{} has requested my public IP address, but the lookup failed.".to_string(...
identifier_body
ip.rs
// STD Dependencies ----------------------------------------------------------- use std::io::Read; // External Dependencies ------------------------------------------------------ use hyper::Client; use hyper::header::Connection;
use ::action::{ActionGroup, MessageActions}; // Command Implementation ----------------------------------------------------- pub struct Handler; impl CommandHandler for Handler { delete_command_message!(); fn run(&self, command: Command) -> ActionGroup { let response = match resolve_ip() { ...
// Internal Dependencies ------------------------------------------------------ use ::command::{Command, CommandHandler};
random_line_split
activation.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/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::C...
fn exit_formal_activation_state(&self) { self.as_element().set_active_state(false); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } } /// Whether an activation was initiated via the click() method #[derive(PartialEq)] ...
{ self.as_element().set_active_state(true); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); }
identifier_body
activation.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/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::C...
use crate::dom::element::Element; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::eventtarget::EventTarget; use crate::dom::mouseevent::MouseEvent; use crate::dom::node::window_from_node; use crate::dom::window::ReflowReason; use script_layout_interface::message::ReflowGoal; use script_tr...
use crate::dom::bindings::str::DOMString;
random_line_split
activation.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/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::C...
target.dispatch_event(event); // Step 5 if let Some(a) = activatable { if event.DefaultPrevented() { a.canceled_activation(); } else { // post click activation a.activation_behavior(event, target); } } // Step 6 element.set_click_in_...
{ event.set_trusted(false); }
conditional_block
activation.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/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::C...
(&self) { self.as_element().set_active_state(true); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } fn exit_formal_activation_state(&self) { self.as_element().set_active_state(false); let win = window_fr...
enter_formal_activation_state
identifier_name
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
}; match byte { b':' => { let packet_len_str = String::from_utf8(buffer).unwrap(); let packet_len = u64::from_str_radix(&packet_len_str, 10).unwrap(); let mut packet = String::new(); self.take(packet_...
let byte = match try!(self.read(&mut buf)) { 0 => return Ok(None), // EOF 1 => buf[0], _ => unreachable!(),
random_line_split
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
<'a>(&mut self) -> io::Result<Option<Json>> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0]; let byte = match try...
read_json_packet
identifier_name
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
fn read_json_packet<'a>(&mut self) -> io::Result<Option<Json>> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0]; ...
{ let s = encode(obj).unwrap().replace("__type__", "type"); println!("<- {}", s); self.write_all(s.len().to_string().as_bytes()).unwrap(); self.write_all(&[':' as u8]).unwrap(); self.write_all(s.as_bytes()).unwrap(); }
identifier_body
provenance.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...
(id: EthDappId) -> Self { DappId(id.into()) } } impl Into<EthDappId> for DappId { fn into(self) -> EthDappId { Into::<String>::into(self).into() } } #[cfg(test)] mod tests { use serde_json; use super::{DappId, Origin}; #[test] fn should_serialize_origin() { // given let o1 = Origin::Rpc("test service"...
from
identifier_name
provenance.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...
// given let id = DappId("testapp".into()); // when let res = serde_json::to_string(&id).unwrap(); // then assert_eq!(res, r#""testapp""#); } #[test] fn should_deserialize_dapp_id() { // given let id = r#""testapp""#; // when let res: DappId = serde_json::from_str(id).unwrap(); // then a...
fn should_serialize_dapp_id() {
random_line_split