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
cli.rs
extern crate tetrs; use std::io::prelude::*; // FIXME! Little hack to clear the screen :) extern "C" { fn system(s: *const u8); } fn clear_screen() { unsafe { system("@clear||cls\0".as_ptr()); }} #[derive(Copy, Clone, Debug, Eq, PartialEq)] enum Input { None, Left, Right, RotateCW, RotateCCW, SoftDrop, HardD...
"H" | "HELP" => Input::Help, _ => Input::Invalid, } } fn bot(state: &mut tetrs::State) -> bool { let weights = tetrs::Weights::default(); let bot = tetrs::PlayI::play(&weights, state.well(), *state.player().unwrap()); if bot.play.len() == 0 { state.hard_drop(); return false; } let mut result = true; for...
random_line_split
object-lifetime-default.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ }
identifier_body
object-lifetime-default.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a,T>(&'a (), T); //~ ERROR None #[rustc_object_lifetime_default] struct C<'a,T:'a>(&'a T); //~ ERROR 'a #[rustc_object_lifetime_default] struct D<'a,'b,T:'a+'b>(&'a T, &'b T); //~ ERROR Ambiguous #[rustc_object_lifetime_default] struct E<'a,'b:'a,T:'b>(&'a T, &'b T); //~ ERROR 'b #[rustc_object_lifetime_default] ...
B
identifier_name
object-lifetime-default.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { }
random_line_split
multi_request.rs
use rand::seq::SliceRandom; use rand::thread_rng; use yaml_rust::Yaml; use crate::interpolator::INTERPOLATION_REGEX; use crate::actions::Request; use crate::benchmark::Benchmark; pub fn is_that_you(item: &Yaml) -> bool
pub fn expand(item: &Yaml, benchmark: &mut Benchmark) { if let Some(with_items) = item["with_items"].as_vec() { let mut with_items_list = with_items.clone(); if let Some(shuffle) = item["shuffle"].as_bool() { if shuffle { let mut rng = thread_rng(); with_items_list.shuffle(&mut rng); ...
{ item["request"].as_hash().is_some() && item["with_items"].as_vec().is_some() }
identifier_body
multi_request.rs
use rand::seq::SliceRandom; use rand::thread_rng; use yaml_rust::Yaml; use crate::interpolator::INTERPOLATION_REGEX; use crate::actions::Request; use crate::benchmark::Benchmark; pub fn is_that_you(item: &Yaml) -> bool { item["request"].as_hash().is_some() && item["with_items"].as_vec().is_some() } pub fn expand(...
() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - foo{{ memory }}"; let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); } }
runtime_expand
identifier_name
multi_request.rs
use rand::seq::SliceRandom; use rand::thread_rng; use yaml_rust::Yaml; use crate::interpolator::INTERPOLATION_REGEX; use crate::actions::Request; use crate::benchmark::Benchmark; pub fn is_that_you(item: &Yaml) -> bool { item["request"].as_hash().is_some() && item["with_items"].as_vec().is_some() } pub fn expand(...
benchmark.push(Box::new(Request::new(item, Some(with_item.clone()), Some(index)))); } } } #[cfg(test)] mod tests { use super::*; #[test] fn expand_multi() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - 3"; let docs = yaml_rust::YamlLoader:...
{ panic!("Interpolations not supported in 'with_items' children!"); }
conditional_block
multi_request.rs
use rand::seq::SliceRandom; use rand::thread_rng; use yaml_rust::Yaml; use crate::interpolator::INTERPOLATION_REGEX; use crate::actions::Request; use crate::benchmark::Benchmark; pub fn is_that_you(item: &Yaml) -> bool { item["request"].as_hash().is_some() && item["with_items"].as_vec().is_some() } pub fn expand(...
let docs = yaml_rust::YamlLoader::load_from_str(text).unwrap(); let doc = &docs[0]; let mut benchmark: Benchmark = Benchmark::new(); expand(&doc, &mut benchmark); } }
fn runtime_expand() { let text = "---\nname: foobar\nrequest:\n url: /api/{{ item }}\nwith_items:\n - 1\n - 2\n - foo{{ memory }}";
random_line_split
fractal_plant.rs
/// https://en.wikipedia.org/wiki/L-system#Example_7:_Fractal_plant extern crate cgmath; #[macro_use] extern crate glium; extern crate glutin; extern crate lsystems; extern crate rand; mod support; use support::prelude::*; use lsystems::alphabet; use lsystems::grammar; #[derive(Debug, Clone, Copy, PartialEq, Eq, Ha...
fn scale(s: f32) -> alphabet::Transform { alphabet::Transform { rotation : 0.0, scale : Vector::new(s, s), } } fn new() -> grammar::T<TextureId> { let s = grammar::Nonterminal(0); let s2 = grammar::Nonterminal(1); let l = grammar::Nonterminal(2); let r = grammar::Nonterm...
{ alphabet::Transform { rotation : std::f32::consts::PI * degrees / 180.0, scale : Vector::new(1.0, 1.0), } }
identifier_body
fractal_plant.rs
/// https://en.wikipedia.org/wiki/L-system#Example_7:_Fractal_plant extern crate cgmath; #[macro_use] extern crate glium; extern crate glutin; extern crate lsystems; extern crate rand; mod support; use support::prelude::*; use lsystems::alphabet; use lsystems::grammar; #[derive(Debug, Clone, Copy, PartialEq, Eq, Ha...
{ Stem, } impl rand::Rand for TextureId { fn rand<Rng: rand::Rng>(_: &mut Rng) -> Self { TextureId::Stem } } impl support::Texture for TextureId { fn to_fragment_shader(&self) -> String { match self { &TextureId::Stem => " #version 330 in vec2 f_texture_posn; out vec4 ...
TextureId
identifier_name
fractal_plant.rs
/// https://en.wikipedia.org/wiki/L-system#Example_7:_Fractal_plant extern crate cgmath; #[macro_use] extern crate glium; extern crate glutin; extern crate lsystems; extern crate rand; mod support; use support::prelude::*; use lsystems::alphabet; use lsystems::grammar; #[derive(Debug, Clone, Copy, PartialEq, Eq, Ha...
} float random( float f ) { const uint mantissaMask = 0x007FFFFFu; const uint one = 0x3F800000u; uint h = hash( floatBitsToUint( f ) ); h &= mantissaMask; h |= one; float r2 = uintBitsToFloat( h ); return r2 - 1.0; ...
x ^= ( x >> 11u ); x += ( x << 15u ); return x;
random_line_split
castingsource0.rs
// Supprime tous les avertissements relatifs aux dépassements // de capacité (e.g. une variable de type u8 ne peut pas // contenir plus qu'une variable de type u16). #![allow(overflowing_literals)] fn main() {
// 1000 - 256 - 256 - 256 = 232 // En réalité, les 8 premiers bits les plus faibles (LSB) sont conservés et les // bits les plus forts (MSB) restants sont tronqués. println!("1000 as a u8 is : {}", 1000 as u8); // -1 + 256 = 255 println!(" -1 as a u8 is : {}", (-1i8) as u8); // Pour les n...
let decimal = 65.4321_f32; // Erreur! La conversion implicite n'est pas supportée. // let integer: u8 = decimal; // FIXME ^ Décommentez/Commentez cette ligne pour voir // le message d'erreur apparaître/disparaître. // Conversion explicite. let integer = decimal as u8; let character = ...
identifier_body
castingsource0.rs
// Supprime tous les avertissements relatifs aux dépassements // de capacité (e.g. une variable de type u8 ne peut pas // contenir plus qu'une variable de type u16). #![allow(overflowing_literals)] fn ma
{ let decimal = 65.4321_f32; // Erreur! La conversion implicite n'est pas supportée. // let integer: u8 = decimal; // FIXME ^ Décommentez/Commentez cette ligne pour voir // le message d'erreur apparaître/disparaître. // Conversion explicite. let integer = decimal as u8; let character...
in()
identifier_name
castingsource0.rs
// Supprime tous les avertissements relatifs aux dépassements // de capacité (e.g. une variable de type u8 ne peut pas // contenir plus qu'une variable de type u16). #![allow(overflowing_literals)] fn main() { let decimal = 65.4321_f32; // Erreur! La conversion implicite n'est pas supportée. // let inte...
}
println!(" 232 as a i8 is : {}", 232 as i8);
random_line_split
htmlvideoelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLVideoElementBinding; use dom::bindings::js::Root; use dom::document::Doc...
{ htmlmediaelement: HTMLMediaElement } impl HTMLVideoElement { fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLVideoElement { HTMLVideoElement { htmlmediaelement: HTMLMediaElement::new_inherited(localName, prefix, document) ...
HTMLVideoElement
identifier_name
htmlvideoelement.rs
use dom::bindings::codegen::Bindings::HTMLVideoElementBinding; use dom::bindings::js::Root; use dom::document::Document; use dom::htmlmediaelement::HTMLMediaElement; use dom::node::Node; use util::str::DOMString; #[dom_struct] pub struct HTMLVideoElement { htmlmediaelement: HTMLMediaElement } impl HTMLVideoEleme...
/* 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/. */
random_line_split
cmac.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
if tag_size > MAX_TAG_LENGTH_IN_BYTES { return Err("Tag size too long".into()); } Ok(()) }
{ return Err("Tag size too short".into()); }
conditional_block
cmac.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
return Err("Tag size too short".into()); } if tag_size > MAX_TAG_LENGTH_IN_BYTES { return Err("Tag size too long".into()); } Ok(()) }
random_line_split
cmac.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
(&self, data: &[u8]) -> Result<Vec<u8>, TinkError> { self.prf.compute_prf(data, self.tag_size) } } /// Validate the parameters for an AES-CMAC against the recommended parameters. pub fn validate_cmac_params(key_size: usize, tag_size: usize) -> Result<(), TinkError> { if key_size!= RECOMMENDED_CMAC_KEY_...
compute_mac
identifier_name
cmac.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
{ if key_size != RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES { return Err(format!( "Only {} sized keys are allowed with Tink's AES-CMAC", RECOMMENDED_CMAC_KEY_SIZE_IN_BYTES ) .into()); } if tag_size < MIN_TAG_LENGTH_IN_BYTES { return Err("Tag size too short".in...
identifier_body
shadowroot.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado...
/// Add a stylesheet owned by `owner` to the list of shadow root sheets, in the /// correct tree position. #[allow(unrooted_must_root)] // Owner needs to be rooted already necessarily. pub fn add_stylesheet(&self, owner: &Element, sheet: Arc<Stylesheet>) { let stylesheets = &mut self.author_st...
{ let stylesheets = &self.author_styles.borrow().stylesheets; stylesheets .get(index) .and_then(|s| s.owner.upcast::<Node>().get_cssom_stylesheet()) }
identifier_body
shadowroot.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado...
(&self) -> Option<DomRoot<Element>> { //XXX get retargeted focused element None } pub fn stylesheet_count(&self) -> usize { self.author_styles.borrow().stylesheets.len() } pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> { let stylesheets = &s...
get_focused_element
identifier_name
shadowroot.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado...
, None => None, } } // https://drafts.csswg.org/cssom-view/#dom-document-elementsfrompoint fn ElementsFromPoint(&self, x: Finite<f64>, y: Finite<f64>) -> Vec<DomRoot<Element>> { // Return the result of running the retargeting algorithm with context object // and the orig...
{ let retargeted_node = self.upcast::<Node>().retarget(e.upcast::<Node>()); retargeted_node .downcast::<Element>() .map(|n| DomRoot::from_ref(n)) }
conditional_block
shadowroot.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::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::ShadowRootBinding::Shado...
pub fn stylesheet_count(&self) -> usize { self.author_styles.borrow().stylesheets.len() } pub fn stylesheet_at(&self, index: usize) -> Option<DomRoot<CSSStyleSheet>> { let stylesheets = &self.author_styles.borrow().stylesheets; stylesheets .get(index) .and_th...
random_line_split
connector.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::hosts::replace_host; use crate::http_loader::Decoder; use flate2::read::GzDecoder; use hyper::body::Pa...
decoder.get_mut().get_mut().extend(chunk.as_ref()); let len = decoder.read(&mut buf).ok()?; buf.truncate(len); Some(buf.into()) }, Decoder::Brotli(ref mut decod...
{ match self.decoder { Decoder::Plain => Some(chunk), Decoder::Gzip(Some(ref mut decoder)) => { let mut buf = vec![0; BUF_SIZE]; decoder.get_mut().get_mut().extend(chunk.as_ref()); ...
conditional_block
connector.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::hosts::replace_host; use crate::http_loader::Decoder; use flate2::read::GzDecoder; use hyper::body::Pa...
let cert = x509::X509::from_pem(cert.as_bytes()).unwrap(); ssl_connector_builder .cert_store_mut() .add_cert(cert) .or_else(|e| { let v: Option<Option<&str>> = e.errors().iter().nth(0).map(|e| e.reason()); if v ...
loop { let token = "-----END CERTIFICATE-----"; if let Some(index) = certs.find(token) { let (cert, rest) = certs.split_at(index + token.len()); certs = rest;
random_line_split
connector.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::hosts::replace_host; use crate::http_loader::Decoder; use flate2::read::GzDecoder; use hyper::body::Pa...
(&mut self) -> Result<Async<Option<Self::Data>>, Self::Error> { self.body.poll_data() } } impl Stream for WrappedBody { type Item = <Body as Stream>::Item; type Error = <Body as Stream>::Error; fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> { self.body.poll().map(|...
poll_data
identifier_name
connector.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::hosts::replace_host; use crate::http_loader::Decoder; use flate2::read::GzDecoder; use hyper::body::Pa...
} pub type Connector = HttpsConnector<HttpConnector>; pub struct WrappedBody { pub body: Body, pub decoder: Decoder, } impl WrappedBody { pub fn new(body: Body) -> Self { Self::new_with_decoder(body, Decoder::Plain) } pub fn new_with_decoder(body: Body, decoder: Decoder) -> Self { ...
{ // Perform host replacement when making the actual TCP connection. let mut new_dest = dest.clone(); let addr = replace_host(dest.host()); new_dest.set_host(&*addr).unwrap(); self.inner.connect(new_dest) }
identifier_body
what_is_going_on.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct UnknownUnits { pub _address: u8, } #[test] fn bindgen_test_layout_UnknownUnits() { assert_eq!( ...
#[repr(C)] #[derive(Debug, Copy, Clone)] pub struct PointTyped<F> { pub x: F, pub y: F, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<F>>, } impl<F> Default for PointTyped<F> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type IntPoint = PointTyped<f32>...
concat!("Alignment of ", stringify!(UnknownUnits)) ); } pub type Float = f32;
random_line_split
what_is_going_on.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct UnknownUnits { pub _address: u8, } #[test] fn bindgen_test_layout_UnknownUnits()
pub type Float = f32; #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct PointTyped<F> { pub x: F, pub y: F, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<F>>, } impl<F> Default for PointTyped<F> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type Int...
{ assert_eq!( ::std::mem::size_of::<UnknownUnits>(), 1usize, concat!("Size of: ", stringify!(UnknownUnits)) ); assert_eq!( ::std::mem::align_of::<UnknownUnits>(), 1usize, concat!("Alignment of ", stringify!(UnknownUnits)) ); }
identifier_body
what_is_going_on.rs
/* automatically generated by rust-bindgen */ #![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct UnknownUnits { pub _address: u8, } #[test] fn bindgen_test_layout_UnknownUnits() { assert_eq!( ...
<F> { pub x: F, pub y: F, pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<F>>, } impl<F> Default for PointTyped<F> { fn default() -> Self { unsafe { ::std::mem::zeroed() } } } pub type IntPoint = PointTyped<f32>;
PointTyped
identifier_name
future-prelude-collision-turbofish.rs
// See https://github.com/rust-lang/rust/issues/88442 // run-rustfix // edition:2018 // check-pass #![allow(unused)] #![warn(rust_2021_prelude_collisions)] trait AnnotatableTryInto { fn try_into<T>(self) -> Result<T, Self::Error> where Self: std::convert::TryInto<T> { std::convert::TryInto::try_into(se...
{ let x: u64 = 1; x.try_into::<usize>().or(Err("foo"))?.checked_sub(1); //~^ WARNING trait method `try_into` will become ambiguous in Rust 2021 //~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! x.try_into::<usize>().or(Err("foo"))?; //~^ WARNING ...
identifier_body
future-prelude-collision-turbofish.rs
// See https://github.com/rust-lang/rust/issues/88442
// run-rustfix // edition:2018 // check-pass #![allow(unused)] #![warn(rust_2021_prelude_collisions)] trait AnnotatableTryInto { fn try_into<T>(self) -> Result<T, Self::Error> where Self: std::convert::TryInto<T> { std::convert::TryInto::try_into(self) } } impl<T> AnnotatableTryInto for T where T:...
random_line_split
future-prelude-collision-turbofish.rs
// See https://github.com/rust-lang/rust/issues/88442 // run-rustfix // edition:2018 // check-pass #![allow(unused)] #![warn(rust_2021_prelude_collisions)] trait AnnotatableTryInto { fn try_into<T>(self) -> Result<T, Self::Error> where Self: std::convert::TryInto<T> { std::convert::TryInto::try_into(se...
() -> Result<(), &'static str> { let x: u64 = 1; x.try_into::<usize>().or(Err("foo"))?.checked_sub(1); //~^ WARNING trait method `try_into` will become ambiguous in Rust 2021 //~| WARNING this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021! x.try_into::<usize>().or(...
main
identifier_name
capturing-logging.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
impl Logger for MyWriter { fn log(&mut self, _level: u32, args: &fmt::Arguments) { let MyWriter(ref mut inner) = *self; fmt::writeln(inner as &mut Writer, args); } } #[start] fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, proc() { main(); }) } fn main() { ...
use std::io::{ChanReader, ChanWriter}; use log::{set_logger, Logger}; struct MyWriter(ChanWriter);
random_line_split
capturing-logging.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 ...
(argc: int, argv: **u8) -> int { native::start(argc, argv, proc() { main(); }) } fn main() { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); spawn(proc() { set_logger(~MyWriter(w) as ~Logger:Send); debug!("debug"); info!("info")...
start
identifier_name
capturing-logging.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 ...
} #[start] fn start(argc: int, argv: **u8) -> int { native::start(argc, argv, proc() { main(); }) } fn main() { let (tx, rx) = channel(); let (mut r, w) = (ChanReader::new(rx), ChanWriter::new(tx)); spawn(proc() { set_logger(~MyWriter(w) as ~Logger:Send); debug!("debug"); ...
{ let MyWriter(ref mut inner) = *self; fmt::writeln(inner as &mut Writer, args); }
identifier_body
main.rs
extern crate ncurses; use std::io; use std::convert::AsRef; use ncurses::*; const CONFIRM_STRING: &'static str = "y"; const OUTPUT_EXAMPLE: &'static str = "Great Firewall dislike VPN protocol.\nGFW 不喜欢VPN协议。"; fn ex1(s: &str)
initscr(); printw(s); refresh(); getch(); endwin(); } fn main() { let mylocale = LcCategory::all; setlocale(mylocale, "zh_CN.UTF-8"); let mut input = String::new(); println!("[ncurses-rs examples]\n"); println!(" example_1. Press \"{}\" or [Enter] to run it...:", CON...
{
identifier_name
main.rs
extern crate ncurses; use std::io; use std::convert::AsRef; use ncurses::*; const CONFIRM_STRING: &'static str = "y"; const OUTPUT_EXAMPLE: &'static str = "Great Firewall dislike VPN protocol.\nGFW 不喜欢VPN协议。"; fn ex1(s: &str) { initscr(); printw(s);
fn main() { let mylocale = LcCategory::all; setlocale(mylocale, "zh_CN.UTF-8"); let mut input = String::new(); println!("[ncurses-rs examples]\n"); println!(" example_1. Press \"{}\" or [Enter] to run it...:", CONFIRM_STRING); io::stdin().read_line(&mut input) .ok() .ex...
refresh(); getch(); endwin(); }
random_line_split
main.rs
extern crate ncurses; use std::io; use std::convert::AsRef; use ncurses::*; const CONFIRM_STRING: &'static str = "y"; const OUTPUT_EXAMPLE: &'static str = "Great Firewall dislike VPN protocol.\nGFW 不喜欢VPN协议。"; fn ex1(s: &str) { initsc
{ let mylocale = LcCategory::all; setlocale(mylocale, "zh_CN.UTF-8"); let mut input = String::new(); println!("[ncurses-rs examples]\n"); println!(" example_1. Press \"{}\" or [Enter] to run it...:", CONFIRM_STRING); io::stdin().read_line(&mut input) .ok() .expect("Fail...
r(); printw(s); refresh(); getch(); endwin(); } fn main()
identifier_body
borrowck-preserve-box-in-discr.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 ...
@F {f: ref b_x} => { assert_eq!(**b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x))); x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(**b_x)) as uint); assert_eq!(**b_x, 3); assert!(ptr::to_un...
struct F { f: ~int } pub fn main() { let mut x = @F {f: ~3}; match x {
random_line_split
borrowck-preserve-box-in-discr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} }
{ assert_eq!(**b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x))); x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(**b_x)) as uint); assert_eq!(**b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr:...
conditional_block
borrowck-preserve-box-in-discr.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let mut x = @F {f: ~3}; match x { @F {f: ref b_x} => { assert_eq!(**b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(**b_x))); x = @F {f: ~4}; debug!("ptr::to_unsafe_ptr(*b_x) = %x", ptr::to_unsafe_ptr(&(**b_x)) as uint); a...
main
identifier_name
state.rs
use specs::{Component, VecStorage}; use specs_derive::*; use super::intent::{AttackType, DefendType, XAxis, YAxis}; use super::Facing; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum HitType { Chopped, Sliced, } #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum Action { Idle, Move { x: XAxi...
pub direction: Facing, pub length: u32, pub ticks: u32, }
random_line_split
state.rs
use specs::{Component, VecStorage}; use specs_derive::*; use super::intent::{AttackType, DefendType, XAxis, YAxis}; use super::Facing; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum
{ Chopped, Sliced, } #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum Action { Idle, Move { x: XAxis, y: YAxis }, Attack(AttackType), AttackRecovery, Defend(DefendType), Hit(HitType), Death(String), Dead, Entrance, } impl Action { pub fn is_attack(&self) -> bool {...
HitType
identifier_name
state.rs
use specs::{Component, VecStorage}; use specs_derive::*; use super::intent::{AttackType, DefendType, XAxis, YAxis}; use super::Facing; #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum HitType { Chopped, Sliced, } #[derive(Debug, Clone, Hash, Eq, PartialEq)] pub enum Action { Idle, Move { x: XAxi...
else { false } } pub fn is_throw_dagger(&self) -> bool { if let Action::Attack(AttackType::ThrowDagger) = self { true } else { false } } } impl Default for Action { fn default() -> Action { Action::Entrance } } #[derive(...
{ true }
conditional_block
regions-variance-contravariant-use-contravariant.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 ...
// if 'call <= 'a, which is true, so no error. collapse(&x, c); fn collapse<'b>(x: &'b int, c: Contravariant<'b>) { } } pub fn main() {}
fn use_<'a>(c: Contravariant<'a>) { let x = 3; // 'b winds up being inferred to this call. // Contravariant<'a> <: Contravariant<'call> is true
random_line_split
regions-variance-contravariant-use-contravariant.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 ...
<'a>(c: Contravariant<'a>) { let x = 3; // 'b winds up being inferred to this call. // Contravariant<'a> <: Contravariant<'call> is true // if 'call <= 'a, which is true, so no error. collapse(&x, c); fn collapse<'b>(x: &'b int, c: Contravariant<'b>) { } } pub fn main() {}
use_
identifier_name
regions-variance-contravariant-use-contravariant.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() {}
{ }
identifier_body
htmlbaseelement.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; use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; use dom::bindings::inheritance:...
(&self) -> Url { let href = self.upcast::<Element>().get_attribute(&ns!(), &atom!("href")) .expect("The frozen base url is only defined for base elements \ that have a base url."); let document = document_from_node(self); let base = document.fallback_base_url(); ...
frozen_base_url
identifier_name
htmlbaseelement.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; use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; use dom::bindings::inheritance:...
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLBaseElement> { let element = HTMLBaseElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLBaseElem...
} }
random_line_split
htmlbaseelement.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; use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; use dom::bindings::inheritance:...
if self.upcast::<Element>().has_attribute(&atom!("href")) { let document = document_from_node(self); document.refresh_base_element(); } } } impl VirtualMethods for HTMLBaseElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElemen...
{ return; }
conditional_block
htmlbaseelement.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; use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; use dom::bindings::inheritance:...
/// https://html.spec.whatwg.org/multipage/#frozen-base-url pub fn frozen_base_url(&self) -> Url { let href = self.upcast::<Element>().get_attribute(&ns!(), &atom!("href")) .expect("The frozen base url is only defined for base elements \ that have a base url."); ...
{ let element = HTMLBaseElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLBaseElementBinding::Wrap) }
identifier_body
interrupt.rs
use alloc::boxed::Box; use collections::string::ToString; use fs::{KScheme, Resource, Url, VecResource}; use system::error::Result; pub struct InterruptScheme; static IRQ_NAME: [&'static str; 16] = [ "Programmable Interval Timer", "Keyboard", "Cascade", "Serial 2 and 4", "Serial 1 and 3", "...
_ => "Unknown Interrupt", }; string.push_str(&format!("{:<6X}{:<16}{}\n", interrupt, count, description)); } } } Ok(box VecResource::new("interrupt:".to_string(), string.into_bytes())) } }
0x14 => "Virtualization exception", 0x1E => "Security exception",
random_line_split
interrupt.rs
use alloc::boxed::Box; use collections::string::ToString; use fs::{KScheme, Resource, Url, VecResource}; use system::error::Result; pub struct InterruptScheme; static IRQ_NAME: [&'static str; 16] = [ "Programmable Interval Timer", "Keyboard", "Cascade", "Serial 2 and 4", "Serial 1 and 3", "...
(&mut self, _: Url, _: usize) -> Result<Box<Resource>> { let mut string = format!("{:<6}{:<16}{}\n", "INT", "COUNT", "DESCRIPTION"); { let interrupts = unsafe { &mut *::env().interrupts.get() }; for interrupt in 0..interrupts.len() { let count = interrupts[interr...
open
identifier_name
interrupt.rs
use alloc::boxed::Box; use collections::string::ToString; use fs::{KScheme, Resource, Url, VecResource}; use system::error::Result; pub struct InterruptScheme; static IRQ_NAME: [&'static str; 16] = [ "Programmable Interval Timer", "Keyboard", "Cascade", "Serial 2 and 4", "Serial 1 and 3", "...
fn open(&mut self, _: Url, _: usize) -> Result<Box<Resource>> { let mut string = format!("{:<6}{:<16}{}\n", "INT", "COUNT", "DESCRIPTION"); { let interrupts = unsafe { &mut *::env().interrupts.get() }; for interrupt in 0..interrupts.len() { let count = inte...
{ "interrupt" }
identifier_body
persistence_error.rs
// Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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...
{ /// An error that occurred when recovering from journal #[error("error recovering from journal: {}", _0)] Recovery(&'static str), /// The number of inserted records didn't match the expected amount #[error("wrong insert count: {} expect: {}", got, expect)] WrongInsertCount { /// The ...
ErrorKind
identifier_name
persistence_error.rs
// Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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...
} } impl From<ErrorKind> for Error { fn from(kind: ErrorKind) -> Error { Error { kind, backtrack: trace!(), } } } impl From<ProtoError> for Error { fn from(e: ProtoError) -> Error { match *e.kind() { ProtoErrorKind::Timeout => ErrorKind::Tim...
{ fmt::Display::fmt(&self.kind, f) }
conditional_block
persistence_error.rs
// Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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...
// foreign /// An error got returned by the trust-dns-proto crate #[error("proto error: {0}")] Proto(#[from] ProtoError), /// An error got returned from the rusqlite crate #[cfg(feature = "sqlite")] #[error("sqlite error: {0}")] Sqlite(#[from] rusqlite::Error), /// A request timed...
/// The number of inserted records got: usize, /// The number of records expected to be inserted expect: usize, },
random_line_split
persistence_error.rs
// Copyright 2015-2020 Benjamin Fry <benjaminfry@me.com> // // Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://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...
} impl From<ProtoError> for Error { fn from(e: ProtoError) -> Error { match *e.kind() { ProtoErrorKind::Timeout => ErrorKind::Timeout.into(), _ => ErrorKind::from(e).into(), } } } #[cfg(feature = "sqlite")] impl From<rusqlite::Error> for Error { fn from(e: rusqlite...
{ Error { kind, backtrack: trace!(), } }
identifier_body
round_trip.rs
// Copyright 2019 The Servo 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...
} the_same(BorderStyle::None); the_same(BorderStyle::Solid); the_same(BorderStyle::Double); the_same(BorderStyle::Dotted); the_same(BorderStyle::Dashed); the_same(BorderStyle::Hidden); the_same(BorderStyle::Groove); the_same(BorderStyle::Ridge); the_same(BorderStyle::Inset); ...
{ #[repr(u32)] #[derive(Clone, Copy, Debug, PartialEq, Eq, PeekPoke)] enum BorderStyle { None = 0, Solid = 1, Double = 2, Dotted = 3, Dashed = 4, Hidden = 5, Groove = 6, Ridge = 7, Inset = 8, Outset = 9, } impl Default ...
identifier_body
round_trip.rs
// Copyright 2019 The Servo 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 { BorderStyle::None } } the_same(BorderStyle::None); the_same(BorderStyle::Solid); the_same(BorderStyle::Double); the_same(BorderStyle::Dotted); the_same(BorderStyle::Dashed); the_same(BorderStyle::Hidden); the_same(BorderStyle::Groove); the_same(Borde...
default
identifier_name
round_trip.rs
// Copyright 2019 The Servo 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use peek_poke::{Pee...
//
random_line_split
lib.rs
let mut src = String::new(); io::stdin().read_to_string(&mut src).unwrap(); Some((Input::Str(src), None)) } else { Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))) } } else { None } } // Whether to stop or continue co...
{ Stop, Continue, } impl Compilation { pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation { match self { Compilation::Stop => Compilation::Stop, Compilation::Continue => next() } } } // A trait for customising the compilation process. Off...
Compilation
identifier_name
lib.rs
"-" { let mut src = String::new(); io::stdin().read_to_string(&mut src).unwrap(); Some((Input::Str(src), None)) } else { Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))) } } else { None } } // Whether to stop or conti...
if sess.opts.parse_only || sess.opts.show_span.is_some() || sess.opts.debugging_opts.ast_json_noexpand { control.after_parse.stop = Compilation::Stop; } if sess.opts.no_analysis || sess.opts.debugging_opts.ast_json { control.after_write_deps.stop =...
fn build_controller(&mut self, sess: &Session) -> CompileController<'a> { let mut control = CompileController::basic();
random_line_split
lib.rs
let mut src = String::new(); io::stdin().read_to_string(&mut src).unwrap(); Some((Input::Str(src), None)) } else { Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))) } } else { None } } // Whether to stop or continue co...
let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints() .iter().cloned().partition(|&(_, p)| p); let plugin = sort_lints(plugin); let builtin = sort_lints(builtin); let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups() .iter().cloned().partition(|&(_, _, p)...
{ let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect(); lints.sort_by(|&(x, _): &(&'static str, Vec<lint::LintId>), &(y, _): &(&'static str, Vec<lint::LintId>)| { x.cmp(y) }); lints }
identifier_body
lib.rs
let mut src = String::new(); io::stdin().read_to_string(&mut src).unwrap(); Some((Input::Str(src), None)) } else { Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)))) } } else { None } } // Whether to stop or continue co...
*sess.crate_metadata.borrow_mut() = metadata; for &style in &crate_types { let fname = link::filename_for_input(sess, style, &id, ...
{ let input = match input { Some(input) => input, None => early_error("no input file provided"), }; let attrs = attrs.as_ref().unwrap(); let t_outputs = driver::build_output_filenames(input, ...
conditional_block
util.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. */ //! Utility traits and functions. use num::PrimInt; /// Returns `single` if the given number is 1, or `plural` otherwise. pub(crate) fn p...
/// Convert a byte count to a human-readable representation of the byte count /// using appropriate IEC suffixes. pub(crate) fn byte_count_iec(size: i64) -> String { let suffixes = [ " KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB", ]; byte_count(size, " byte", " bytes", &suffixes) }...
{ const UNIT_LIMIT: i64 = 9999; match (size, multiple.split_last()) { (std::i64::MIN..=UNIT_LIMIT, _) | (_, None) => { format!("{}{}", size, plural(size, unit_single, unit_plural)) } (size, Some((last_multiple, multiple))) => { let mut divisor = 1024; ...
identifier_body
util.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. */ //! Utility traits and functions. use num::PrimInt; /// Returns `single` if the given number is 1, or `plural` otherwise. pub(crate) fn p...
/// Convert a byte count to a human-readable representation of the byte count /// using appropriate IEC suffixes. pub(crate) fn byte_count_iec(size: i64) -> String { let suffixes = [ " KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB", ]; byte_count(size, " byte", " bytes", &suffixes) } ...
} } }
random_line_split
util.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. */ //! Utility traits and functions. use num::PrimInt; /// Returns `single` if the given number is 1, or `plural` otherwise. pub(crate) fn p...
else { plural } } fn byte_count(size: i64, unit_single: &str, unit_plural: &str, multiple: &[&str]) -> String { const UNIT_LIMIT: i64 = 9999; match (size, multiple.split_last()) { (std::i64::MIN..=UNIT_LIMIT, _) | (_, None) => { format!("{}{}", size, plural(size, unit_single, unit_plural))...
{ single }
conditional_block
util.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. */ //! Utility traits and functions. use num::PrimInt; /// Returns `single` if the given number is 1, or `plural` otherwise. pub(crate) fn p...
(size: i64) -> String { let suffixes = [ " KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB", ]; byte_count(size, " byte", " bytes", &suffixes) } /// Convert a byte count to a human-readable representation of the byte count /// using short suffixes. pub(crate) fn byte_count_short(size: i...
byte_count_iec
identifier_name
color.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Color", inherited=True) %> <% fr...
(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { CSSColor::parse(context, input).map(SpecifiedValue) } // FIXME(#15973): Add servo support for system colors % if product == "gecko": <% # These are actually parsed. See nsCSSProps::kColorKTable ...
parse
identifier_name
color.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Color", inherited=True) %> <% fr...
} pub mod computed_value { use cssparser; pub type T = cssparser::RGBA; } #[inline] pub fn get_initial_value() -> computed_value::T { RGBA::new(0, 0, 0, 255) // black } pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> { ...
{ self.0.to_css(dest) }
identifier_body
color.mako.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/. */ <%namespace name="helpers" file="/helpers.mako.rs" /> <% data.new_style_struct("Color", inherited=True) %> <% fr...
#[inline] fn to_computed_value(&self, context: &Context) -> computed_value::T { self.0.parsed.to_computed_value(context) } #[inline] fn from_computed_value(computed: &computed_value::T) -> Self { SpecifiedValue(CSSColor { parsed: Color::RG...
type ComputedValue = computed_value::T;
random_line_split
supportbundle.rs
use crate::{common::ui::{Status, UIWriter, UI}, error::{Error, Result}, hcore::{fs::FS_ROOT_PATH, os::net::hostname}}; use chrono::Local; use flate2::{write::GzEncoder, Compression}; use std::{...
let mut tar = tar::Builder::new(enc); tar.follow_symlinks(false); if sup_root.exists() { ui.status(Status::Adding, format!("files from {}", &sup_root.display()))?; if let Err(why) = tar.append_dir_all(format!("hab{}sup", MAIN_SEPARATOR), &sup_root) { ui.fatal(...
{ let dt = Local::now(); ui.status(Status::Generating, format!("New Support Bundle at {}", dt.format("%Y-%m-%d %H:%M:%S")))?; let host = match lookup_hostname() { Ok(host) => host, Err(e) => { let host = String::from("localhost"); ui.warn(format!("Hostna...
identifier_body
supportbundle.rs
use crate::{common::ui::{Status, UIWriter, UI}, error::{Error, Result}, hcore::{fs::FS_ROOT_PATH, os::net::hostname}}; use chrono::Local; use flate2::{write::GzEncoder, Compression}; use std::{...
Ok(()) }
process::exit(1) } ui.status(Status::Created, format!("{}{}{}", cwd.display(), MAIN_SEPARATOR, &tarball_name))?;
random_line_split
supportbundle.rs
use crate::{common::ui::{Status, UIWriter, UI}, error::{Error, Result}, hcore::{fs::FS_ROOT_PATH, os::net::hostname}}; use chrono::Local; use flate2::{write::GzEncoder, Compression}; use std::{...
() -> Result<String> { match hostname() { Ok(hostname) => Ok(hostname), Err(_) => Err(Error::NameLookup), } } pub fn start(ui: &mut UI) -> Result<()> { let dt = Local::now(); ui.status(Status::Generating, format!("New Support Bundle at {}", dt.format("%Y-%m-%d %H:%M:%S")))...
lookup_hostname
identifier_name
fmt.rs
//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension. //! This macro is implemented in the compiler to emit calls to this module in //! order to format arguments at runtime into strings. //! //! # Usage //! //! The [`format!`] macro i...
rgs.estimated_capacity(); let mut output = string::String::with_capacity(capacity); output.write_fmt(args).expect("a formatting trait implementation returned an error"); output }
identifier_body
fmt.rs
//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension. //! This macro is implemented in the compiler to emit calls to this module in //! order to format arguments at runtime into strings. //! //! # Usage //! //! The [`format!`] macro i...
-> string::String { let capacity = args.estimated_capacity(); let mut output = string::String::with_capacity(capacity); output.write_fmt(args).expect("a formatting trait implementation returned an error"); output }
<'_>)
identifier_name
fmt.rs
//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension. //! This macro is implemented in the compiler to emit calls to this module in //! order to format arguments at runtime into strings. //! //! # Usage //! //! The [`format!`] macro i...
//! println!("Hello {:1$}!", "x", 5); //! println!("Hello {1:0$}!", 5, "x"); //! println!("Hello {:width$}!", "x", width = 5); //! let width = 5; //! println!("Hello {:width$}!", "x"); //! ``` //! //! This is a parameter for the "minimum width" that the format should take up. //! If the value's string does not fill up ...
//! ``` //! // All of these print "Hello x !" //! println!("Hello {:5}!", "x");
random_line_split
regions-fn-subtyping.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 test_fn<'x,'y,'z,T>(_x: &'x T, _y: &'y T, _z: &'z T) { // Here, x, y, and z are free. Other letters // are bound. Note that the arrangement // subtype::<T1>(of::<T2>()) will typecheck // iff T1 <: T2. subtype::<&fn<'a>(&'a T)>( of::<&fn<'a>(&'a T)>()); subtype::<&fn<'a>(&'a T)>(...
{ fail!(); }
identifier_body
regions-fn-subtyping.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>(x: @fn(T)) { fail!(); } fn test_fn<'x,'y,'z,T>(_x: &'x T, _y: &'y T, _z: &'z T) { // Here, x, y, and z are free. Other letters // are bound. Note that the arrangement // subtype::<T1>(of::<T2>()) will typecheck // iff T1 <: T2. subtype::<&fn<'a>(&'a T)>( of::<&fn<'a>(&'a T)>()); ...
subtype
identifier_name
regions-fn-subtyping.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 main() {}
subtype::<&fn<'a,'b>(&'a T) -> @fn(&'b T)>( of::<&fn<'a>(&'a T) -> @fn(&'a T)>());
random_line_split
hilbert_curve.rs
use std::io::{Read, Write}; use std::collections::HashMap; use graph_iterator::EdgeMapper; use byteorder::{ReadBytesExt, WriteBytesExt};
pub fn encode<W: Write>(writer: &mut W, diff: u64) { assert!(diff > 0); for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shift)!= 0 { writer.write_u8(0u8).ok().expect("write error"); } } for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shif...
#[inline]
random_line_split
hilbert_curve.rs
use std::io::{Read, Write}; use std::collections::HashMap; use graph_iterator::EdgeMapper; use byteorder::{ReadBytesExt, WriteBytesExt}; #[inline] pub fn encode<W: Write>(writer: &mut W, diff: u64) { assert!(diff > 0); for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shift)!= 0 { ...
result.0 += (x_byte as u32) << (8 * log_s); result.1 += (y_byte as u32) << (8 * log_s); } debug_assert!(bit_detangle(init_tangle) == result); return result; } } fn bit_entangle(mut pair: (u32, u32)) -> u64 { let mut result = 0u64; for log_s_rev in 0..32 { ...
{ let temp = result.0; result.0 = result.1; result.1 = temp; }
conditional_block
hilbert_curve.rs
use std::io::{Read, Write}; use std::collections::HashMap; use graph_iterator::EdgeMapper; use byteorder::{ReadBytesExt, WriteBytesExt}; #[inline] pub fn encode<W: Write>(writer: &mut W, diff: u64) { assert!(diff > 0); for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shift)!= 0 { ...
(&mut self, tangle: u64) -> (u32, u32) { let (mut x_byte, mut y_byte) = unsafe { *self.hilbert.detangle.get_unchecked(tangle as u16 as usize) }; // validate self.prev_rot, self.prev_out if self.prev_hi!= (tangle >> 16) { self.prev_hi = tangle >> 16; // detangle with a b...
detangle
identifier_name
sha2.rs
self) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { ...
/// * input - A vector of message data fn input(&mut self, input: &[u8]); /// Retrieve the digest result. This method may be called multiple times. /// /// # Arguments /// /// * out - the vector to hold the result. Must be large enough to contain output_bits(). fn result(&mut self, out:...
random_line_split
sha2.rs
) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { le...
} /// The SHA-256 hash algorithm pub struct Sha256 { engine: Engine256 } impl Sha256 { /// Construct a new instance of a SHA-256 digest. pub fn new() -> Sha256 { Sha256 { engine: Engine256::new(&H256) } } } impl Digest for Sha256 { fn input(&mut self, d: &[u8]) { ...
{ if self.finished { return; } let self_state = &mut self.state; self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) }); write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 ); write_u32_be(self.buffer.next(4), self.l...
identifier_body
sha2.rs
) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { le...
(&self) -> uint { 64 - self.buffer_idx } fn size(&self) -> uint { 64 } } /// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct. trait StandardPadding { /// Add padding to the buffer. The buffer must not be full when this method is called and is /// guaranteed to have exactl...
remaining
identifier_name
ty_match.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 ...
(&mut self, a: ty::Region, b: ty::Region) -> RelateResult<'tcx, ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); Ok(a) } fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { ...
regions
identifier_name
ty_match.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 ...
/// A type "A" *matches* "B" if the fresh types in B could be /// substituted with values so as to make it equal to A. Matching is /// intended to be used only on freshened types, and it basically /// indicates if the non-freshened versions of A and B could have been /// unified. /// /// It is only an approximation. If...
random_line_split
ty_match.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 ...
(&ty::ty_err, _) | (_, &ty::ty_err) => { Ok(self.tcx().types.err) } _ => { ty_relate::super_relate_tys(self, a, b) } } } fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> RelateResult<'t...
{ Err(ty::terr_sorts(ty_relate::expected_found(self, &a, &b))) }
conditional_block
ty_match.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 tcx(&self) -> &'a ty::ctxt<'tcx> { self.tcx } fn a_is_expected(&self) -> bool { true } // irrelevant fn relate_with_variance<T:Relate<'a,'tcx>>(&mut self, _: ty::Variance, a: &T, ...
{ "Match" }
identifier_body
sizing.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. */ use crate::graph::{FileContentData, Node, NodeData, NodeType, WrappedPath}; use crate::progress::{ progress_stream, report_state, Progr...
); let compressor = size_sampling_stream( scheduled_max, walk_progress, CompressorType::Zstd { level: command.compression_level, }, command.sampler, ...
{ let sizing_progress_state = ProgressStateMutex::new(ProgressStateCountByType::<SizingStats, SizingStats>::new( fb, repo_params.logger.clone(), COMPRESSION_BENEFIT, repo_params.repo.name().clone(), command.sampling_options.node_types.clone(), ...
identifier_body
sizing.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. */ use crate::graph::{FileContentData, Node, NodeData, NodeType, WrappedPath}; use crate::progress::{ progress_stream, report_state, Progr...
} } fn try_compress(raw_data: &Bytes, compressor_type: CompressorType) -> Result<SizingStats, Error> { let raw = raw_data.len() as u64; let compressed_buf = MeteredWrite::new(Cursor::new(Vec::with_capacity(4 * 1024))); let mut compressor = Compressor::new(compressed_buf, compressor_type); compresso...
random_line_split
sizing.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. */ use crate::graph::{FileContentData, Node, NodeData, NodeType, WrappedPath}; use crate::progress::{ progress_stream, report_state, Progr...
(&mut self) { if let Some(delta_time) = self.should_log_throttled() { self.report_progress_log(Some(delta_time)); } } } #[derive(Debug)] pub struct SizingSample { pub data: HashMap<String, BlobstoreBytes>, } impl Default for SizingSample { fn default() -> Self { Self { ...
report_throttled
identifier_name
sizing.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. */ use crate::graph::{FileContentData, Node, NodeData, NodeType, WrappedPath}; use crate::progress::{ progress_stream, report_state, Progr...
try_compress(v.as_bytes(), compressor_type) .map(|sizes| acc + sizes) }, ) }) .transpose(); ...
{ match fc { FileContentData::Consumed(_num_loaded_bytes) => { future::ok(_num_loaded_bytes).left_future() } // Consume the stream to make sure we loaded all blobs FileContentData::ContentStream(file_...
conditional_block
send_msg.rs
//! Client Node Example. //! //! The node sends a message (atom) to the specified erlang node. //! //! # Usage Examples //! //! ```bash //! $ cargo run --example send_msg -- --help //! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello //! ``` extern crate clap; extern crate ...
.parse() .expect("Invalid epmd address"); let dest_proc = matches.value_of("DESTINATION").unwrap().to_string(); let message = matches.value_of("MESSAGE").unwrap().to_string(); let self_node0 = self_node.to_string(); let mut executor = InPlaceExecutor::new().unwrap(); let monitor = exe...
random_line_split
send_msg.rs
//! Client Node Example. //! //! The node sends a message (atom) to the specified erlang node. //! //! # Usage Examples //! //! ```bash //! $ cargo run --example send_msg -- --help //! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello //! ``` extern crate clap; extern crate ...
.arg( Arg::with_name("COOKIE") .long("cookie") .takes_value(true) .default_value("WPKYDIOSJIMJUURLRUHV"), ) .arg( Arg::with_name("SELF_NODE") .long("self") .takes_value(true) .default_...
{ let matches = App::new("send_msg") .arg( Arg::with_name("EPMD_HOST") .short("h") .takes_value(true) .default_value("127.0.0.1"), ) .arg( Arg::with_name("EPMD_PORT") .short("p") .takes_va...
identifier_body
send_msg.rs
//! Client Node Example. //! //! The node sends a message (atom) to the specified erlang node. //! //! # Usage Examples //! //! ```bash //! $ cargo run --example send_msg -- --help //! $ cargo run --example send_msg -- --peer foo --destination foo --cookie erlang_cookie -m hello //! ``` extern crate clap; extern crate ...
}) .and_then(move |peer| { // Sends a message to the peer node println!("# Connected: {}", peer.name); println!("# Distribution Flags: {:?}", peer.flags); let tx = channel::sender(peer.stream); let from_pid = eetf::P...
{ Either::B(futures::failed(Error::new( ErrorKind::NotFound, "target node is not found", ))) }
conditional_block