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
render.rs
use syntax::ast::{Expr, Ident, Pat, Stmt, TokenTree}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::parse::token; use syntax::ptr::P; use maud; #[derive(Copy, Clone)] pub enum Escape { PassThru, Escape, } pub struct Renderer<'cx> { pub cx: &'cx ExtCtxt<'cx>, w: Ident...
} }
let stmt = quote_stmt!(self.cx, for $pattern in $iterable { $body }).unwrap(); self.push(stmt);
random_line_split
render.rs
use syntax::ast::{Expr, Ident, Pat, Stmt, TokenTree}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::parse::token; use syntax::ptr::P; use maud; #[derive(Copy, Clone)] pub enum Escape { PassThru, Escape, } pub struct Renderer<'cx> { pub cx: &'cx ExtCtxt<'cx>, w: Ident...
(&mut self, name: &str) { self.push_str(" "); self.push_str(name); self.push_str("=\""); } pub fn attribute_empty(&mut self, name: &str) { self.push_str(" "); self.push_str(name); } pub fn attribute_end(&mut self) { self.push_str("\""); } pub fn...
attribute_start
identifier_name
enum_explicit_type.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(u8)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum Foo { Bar = 0, Qux = 1, } #[repr(i8)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum Neg { MinusOne = -1, One = 1, } ...
{ MuchLow = -4294967296, } #[repr(i64)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum MuchLongLong { I64_MIN = -9223372036854775808, } #[repr(u64)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum MuchULongLong { MuchHigh = 4294967296, } #[repr(u8)] #[derive(Debug, Copy, Clone, Has...
MuchLong
identifier_name
enum_explicit_type.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(u8)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum Foo { Bar = 0, Qux = 1, }
pub enum Neg { MinusOne = -1, One = 1, } #[repr(u16)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum Bigger { Much = 255, Larger = 256, } #[repr(i64)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum MuchLong { MuchLow = -4294967296, } #[repr(i64)] #[derive(Debug, Copy, Clone...
#[repr(i8)] #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
random_line_split
constellation_msg.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/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling...
{ pub width: u32, pub height: u32, pub format: PixelFormat, #[ignore_heap_size_of = "Defined in ipc-channel"] pub bytes: IpcSharedMemory, } /// Similar to net::resource_task::LoadData /// can be passed to LoadUrl to load a page with GET/POST /// parameters or headers #[derive(Clone, Deserialize, S...
Image
identifier_name
constellation_msg.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/. */ //! The high-level interface from script to constellation. Using this abstract interface helps //! reduce coupling...
impl PipelineNamespace { pub fn install(namespace_id: PipelineNamespaceId) { PIPELINE_NAMESPACE.with(|tls| { assert!(tls.get().is_none()); tls.set(Some(PipelineNamespace { id: namespace_id, next_index: PipelineIndex(0), })); }); ...
id: PipelineNamespaceId, next_index: PipelineIndex, }
random_line_split
build_schema.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::compiler_state::CompilerState; use crate::config::ProjectConfig; use schema::Schema; pub fn
(compiler_state: &CompilerState, project_config: &ProjectConfig) -> Schema { let relay_extensions = String::from(schema::RELAY_EXTENSIONS); let mut extensions = vec![&relay_extensions]; if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) { extensions.extend(project_...
build_schema
identifier_name
build_schema.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::compiler_state::CompilerState; use crate::config::ProjectConfig; use schema::Schema; pub fn build_schema(compiler_state...
{ let relay_extensions = String::from(schema::RELAY_EXTENSIONS); let mut extensions = vec![&relay_extensions]; if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) { extensions.extend(project_extensions); } if let Some(base_project_name) = project_config.base...
identifier_body
build_schema.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::compiler_state::CompilerState; use crate::config::ProjectConfig; use schema::Schema; pub fn build_schema(compiler_state...
} let mut schema_sources = Vec::new(); schema_sources.extend( compiler_state.schemas[&project_config.name] .iter() .map(String::as_str), ); schema::build_schema_with_extensions(&schema_sources, &extensions).unwrap() }
{ extensions.extend(base_project_extensions); }
conditional_block
build_schema.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::compiler_state::CompilerState; use crate::config::ProjectConfig; use schema::Schema; pub fn build_schema(compiler_state...
if let Some(base_project_name) = project_config.base { if let Some(base_project_extensions) = compiler_state.extensions.get(&base_project_name) { extensions.extend(base_project_extensions); } } let mut schema_sources = Vec::new(); schema_sources.extend( compiler_state...
let relay_extensions = String::from(schema::RELAY_EXTENSIONS); let mut extensions = vec![&relay_extensions]; if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) { extensions.extend(project_extensions); }
random_line_split
util.rs
use std::fmt::Debug; #[macro_export] macro_rules! unwrap_msg ( ($e:expr) => ( ($e).unwrap_log(file!(), line!(), module_path!(), stringify!($e)) ) ); pub trait UnwrapLog<T> { fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T; } impl<T> UnwrapLog<T> for Option<T> { fn un...
(self, file: &str, line: u32, module_path: &str, expression: &str) -> T { match self { Ok(t) => t, Err(e) => panic!("{}:{} {} this should not have panicked:\ntried to unwrap Err({:?}) in\nunwrap_msg!({})", file, line, module_path, e, expression) } } } #[macro_export] macro_rules! assert_size ( ...
unwrap_log
identifier_name
util.rs
use std::fmt::Debug; #[macro_export] macro_rules! unwrap_msg ( ($e:expr) => ( ($e).unwrap_log(file!(), line!(), module_path!(), stringify!($e)) ) ); pub trait UnwrapLog<T> { fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T; } impl<T> UnwrapLog<T> for Option<T> { fn un...
);
#[macro_export] macro_rules! assert_size ( ($t:ty, $sz:expr) => ( assert_eq!(::std::mem::size_of::<$t>(), $sz); );
random_line_split
util.rs
use std::fmt::Debug; #[macro_export] macro_rules! unwrap_msg ( ($e:expr) => ( ($e).unwrap_log(file!(), line!(), module_path!(), stringify!($e)) ) ); pub trait UnwrapLog<T> { fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T; } impl<T> UnwrapLog<T> for Option<T> { fn un...
} impl<T,E:Debug> UnwrapLog<T> for Result<T,E> { fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T { match self { Ok(t) => t, Err(e) => panic!("{}:{} {} this should not have panicked:\ntried to unwrap Err({:?}) in\nunwrap_msg!({})", file, line, module_path, e, exp...
{ match self { Some(t) => t, None => panic!("{}:{} {} this should not have panicked:\ntried to unwrap `None` in:\nunwrap_msg!({})", file, line, module_path, expression) } }
identifier_body
text.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" /> <% from data import Method %> <% data.new_style_struct("Tex...
let mut empty = true; loop { let result: Result<_, ParseError> = input.try(|input| { let location = input.current_source_location(); match input.expect_ident() { Ok(ident) => { (match_ignore_ascii_case! { &ident, ...
{ return Ok(result) }
conditional_block
text.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" /> <% from data import Method %> <% data.new_style_struct("Tex...
() -> computed_value::T { computed_value::none } #[inline] pub fn get_initial_specified_value() -> SpecifiedValue { SpecifiedValue::empty() } /// none | [ underline || overline || line-through || blink ] pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>) ...
get_initial_value
identifier_name
text.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" /> <% from data import Method %> <% data.new_style_struct("Tex...
else { empty = false; result.insert(BLINK); Ok(()) }, _ => Err(()) }).map_err(|()| { location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone())) }) ...
{ let mut result = SpecifiedValue::empty(); if input.try(|input| input.expect_ident_matching("none")).is_ok() { return Ok(result) } let mut empty = true; loop { let result: Result<_, ParseError> = input.try(|input| { let location = input.c...
identifier_body
text.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" /> <% from data import Method %> <% data.new_style_struct("Tex...
let location = input.current_source_location(); match input.expect_ident() { Ok(ident) => { (match_ignore_ascii_case! { &ident, "underline" => if result.contains(UNDERLINE) { Err(()) } ...
} let mut empty = true; loop { let result: Result<_, ParseError> = input.try(|input| {
random_line_split
htmlstyleelement.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 as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTM...
fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } if tree_in_doc { self.parse_own_css(); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#d...
if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } }
random_line_split
htmlstyleelement.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 as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTM...
(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> Root<HTMLStyleElement> { Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document), document, HTMLStyleElementBinding::Wrap) ...
new
identifier_name
htmlstyleelement.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 as CssParser; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTM...
pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let win = window_from_node(node); let url = win.get_url(); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); ...
{ Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document), document, HTMLStyleElementBinding::Wrap) }
identifier_body
repl.rs
//! Helpers for replacing values in a message template. //! //! All properties in the template must be of the form: `"{label}"`. //! Use either `MessageTempalte::new()` or `MessageTemplate::from_format()` to make sure //! it's in the right format. use std::collections::BTreeMap; use std::str; use events::Value; use s...
} (ctr, &i[ctr..]) } #[cfg(test)] mod tests { use std::collections::BTreeMap; use ::templates::repl::MessageTemplateRepl; #[test] fn values_are_replaced() { let template_repl = MessageTemplateRepl::new("C {A} D {Bert} E"); let mut map = BTreeMap::new(); map.insert("A...
{ break; }
conditional_block
repl.rs
//! Helpers for replacing values in a message template. //! //! All properties in the template must be of the form: `"{label}"`. //! Use either `MessageTempalte::new()` or `MessageTemplate::from_format()` to make sure //! it's in the right format.
use events::Value; use std::fmt::Write; pub struct MessageTemplateRepl<'a> { text: &'a str, param_slices: Vec<ParamSlice> } impl <'a> MessageTemplateRepl<'a> { pub fn new(text: &'a str) -> MessageTemplateRepl { let slices = parse_slices( text.as_bytes(), State::Lit(0), ...
use std::collections::BTreeMap; use std::str;
random_line_split
repl.rs
//! Helpers for replacing values in a message template. //! //! All properties in the template must be of the form: `"{label}"`. //! Use either `MessageTempalte::new()` or `MessageTemplate::from_format()` to make sure //! it's in the right format. use std::collections::BTreeMap; use std::str; use events::Value; use s...
<F>(i: &[u8], f: F) -> (usize, &[u8]) where F: Fn(u8) -> bool { let mut ctr = 0; for c in i { if f(*c) { ctr += 1; } else { break; } } (ctr, &i[ctr..]) } #[cfg(test)] mod tests { use std::collections::BTreeMap; use ::templates::repl::Mes...
shift_while
identifier_name
repl.rs
//! Helpers for replacing values in a message template. //! //! All properties in the template must be of the form: `"{label}"`. //! Use either `MessageTempalte::new()` or `MessageTemplate::from_format()` to make sure //! it's in the right format. use std::collections::BTreeMap; use std::str; use events::Value; use s...
fn shift(i: &[u8], c: usize) -> (usize, &[u8]) { match c { c if c >= i.len() => (i.len(), &[]), _ => (c, &i[c..]) } } fn shift_while<F>(i: &[u8], f: F) -> (usize, &[u8]) where F: Fn(u8) -> bool { let mut ctr = 0; for c in i { if f(*c) { ctr += 1; } ...
{ let mut ctr = 0; for c in i { if f(*c) { ctr += 1; } else { break; } } (ctr, &i[ctr..], str::from_utf8(&i[0..ctr]).unwrap()) }
identifier_body
readcsv.rs
/// /// This example parses, sorts and groups the iris dataset /// and does some simple manipulations. /// /// Iterators and itertools functionality are used throughout. /// /// use ndarray::Array; use dataframe::DataFrame; use util::traits::UtahNum; use util::error::*; use util::traits::Constructor; use rustc_seriali...
(file: &'static str) -> Result<DataFrame<T>> { let mut rdr = csv::Reader::from_file(file).unwrap(); let columns = rdr.headers().unwrap(); let (mut nrow, ncol) = (0, columns.len()); let mut v: Vec<T> = Vec::new(); for record in rdr.decode() { nrow += 1; let...
read_csv
identifier_name
readcsv.rs
/// /// This example parses, sorts and groups the iris dataset /// and does some simple manipulations. /// /// Iterators and itertools functionality are used throughout. /// /// use ndarray::Array; use dataframe::DataFrame; use util::traits::UtahNum; use util::error::*; use util::traits::Constructor; use rustc_seriali...
}
{ let mut rdr = csv::Reader::from_file(file).unwrap(); let columns = rdr.headers().unwrap(); let (mut nrow, ncol) = (0, columns.len()); let mut v: Vec<T> = Vec::new(); for record in rdr.decode() { nrow += 1; let e: Vec<T> = record.unwrap(); v.e...
identifier_body
readcsv.rs
/// /// This example parses, sorts and groups the iris dataset /// and does some simple manipulations. /// /// Iterators and itertools functionality are used throughout. /// /// use ndarray::Array; use dataframe::DataFrame; use util::traits::UtahNum; use util::error::*; use util::traits::Constructor; use rustc_seriali...
let e: Vec<T> = record.unwrap(); v.extend(e.into_iter()) } let matrix = Array::from_shape_vec((nrow, ncol), v).unwrap(); DataFrame::new(matrix).columns(&columns[..]) } }
for record in rdr.decode() { nrow += 1;
random_line_split
error.rs
use std::error::Error; use std::fmt::{Display, Formatter}; use std::fmt::Result as FmtResult; use std::io; use fmt::Format; pub type CliResult<T> = Result<T, CliError>; #[derive(Debug)] #[allow(dead_code)] pub enum CliErrorKind { UnknownBoolArg, TomlTableRoot, TomlNoName, CurrentDir, Unknown, ...
(ioe: io::Error) -> Self { CliError { error: format!("{} {}", Format::Error("error:"), ioe.description()), kind: CliErrorKind::Io(ioe), } } }
from
identifier_name
error.rs
use std::error::Error; use std::fmt::{Display, Formatter}; use std::fmt::Result as FmtResult; use std::io; use fmt::Format; pub type CliResult<T> = Result<T, CliError>; #[derive(Debug)] #[allow(dead_code)] pub enum CliErrorKind { UnknownBoolArg, TomlTableRoot, TomlNoName, CurrentDir,
Io(io::Error), Generic(String), } impl CliErrorKind { fn description(&self) -> &str { match *self { CliErrorKind::Generic(ref e) => e, CliErrorKind::TomlTableRoot => "No root table found for toml file", CliErrorKind::TomlNoName => "No name for package in toml fil...
Unknown,
random_line_split
error.rs
use std::error::Error; use std::fmt::{Display, Formatter}; use std::fmt::Result as FmtResult; use std::io; use fmt::Format; pub type CliResult<T> = Result<T, CliError>; #[derive(Debug)] #[allow(dead_code)] pub enum CliErrorKind { UnknownBoolArg, TomlTableRoot, TomlNoName, CurrentDir, Unknown, ...
}
{ CliError { error: format!("{} {}", Format::Error("error:"), ioe.description()), kind: CliErrorKind::Io(ioe), } }
identifier_body
quick.rs
#![cfg_attr(feature = "qc", feature(plugin, custom_attribute))] #![cfg_attr(feature="qc", plugin(quickcheck_macros))] #![allow(dead_code)] //! The purpose of these tests is to cover corner cases of iterators //! and adaptors. //! //! In particular we test the tedious size_hint and exact size correctness. #[macro_use]...
if stride == 0 { // never zero stride += 1; } if stride > 0 { itertools::equal(Stride::from_slice(&data, stride as isize), data.iter().step(stride as usize)) } else { itertools::equal(Stride::from_slice(&data, stride as isize), ...
fn equal_stride(data: Vec<u8>, mut stride: i8) -> bool {
random_line_split
quick.rs
#![cfg_attr(feature = "qc", feature(plugin, custom_attribute))] #![cfg_attr(feature="qc", plugin(quickcheck_macros))] #![allow(dead_code)] //! The purpose of these tests is to cover corner cases of iterators //! and adaptors. //! //! In particular we test the tedious size_hint and exact size correctness. #[macro_use]...
#[quickcheck] fn size_2_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool { let it = a.clone().zip_longest(b.clone()); let jt = a.clone().zip_longest(b.clone()); itertools::equal(a.clone(), it.filter_map(|elt| match elt { EitherOrBoth::Both(x, _) => Some(x), ...
{ let filt = a.clone().dedup(); let filt2 = b.clone().dedup(); correct_size_hint(filt.zip_longest(b.clone())) && correct_size_hint(a.clone().zip_longest(filt2)) && exact_size(a.zip_longest(b)) }
identifier_body
quick.rs
#![cfg_attr(feature = "qc", feature(plugin, custom_attribute))] #![cfg_attr(feature="qc", plugin(quickcheck_macros))] #![allow(dead_code)] //! The purpose of these tests is to cover corner cases of iterators //! and adaptors. //! //! In particular we test the tedious size_hint and exact size correctness. #[macro_use]...
(a: Vec<i32>, x: i32) -> bool { let mut inter = false; let mut i = 0; for elt in a.iter().cloned().intersperse(x) { if inter { if elt!= x { return false } } else { if elt!= a[i] { return false } i += 1; } inter =!inter; } true } #[...
equal_intersperse
identifier_name
quick.rs
#![cfg_attr(feature = "qc", feature(plugin, custom_attribute))] #![cfg_attr(feature="qc", plugin(quickcheck_macros))] #![allow(dead_code)] //! The purpose of these tests is to cover corner cases of iterators //! and adaptors. //! //! In particular we test the tedious size_hint and exact size correctness. #[macro_use]...
} #[quickcheck] fn size_product(a: Iter<u16>, b: Iter<u16>) -> bool { correct_size_hint(a.cartesian_product(b)) } #[quickcheck] fn size_product3(a: Iter<u16>, b: Iter<u16>, c: Iter<u16>) -> bool { correct_size_hint(iproduct!(a, b, c)) } #[quickcheck] fn size_step(a: Iter<i16>, mut s: usize) -> bool { if...
{ itertools::equal(Stride::from_slice(&data, stride as isize), data.iter().rev().step(-stride as usize)) }
conditional_block
http_test.rs
#[cfg(all(feature = "metrics", feature = "rt-tokio"))] mod test { use http::header::{HeaderValue, AUTHORIZATION, USER_AGENT}; use hyper::{ body, service::{make_service_fn, service_fn}, Body, Method, Request, Response, Server, }; use opentelemetry::{global, Key, KeyValue}; use...
Ok::<_, hyper::Error>( Response::builder() .status(http::StatusCode::METHOD_NOT_ALLOWED) .body(Body::empty()) .unwrap(), ...
{ let (addr_tx, addr_rx) = tokio::sync::oneshot::channel(); let (req_tx, mut req_rx) = tokio::sync::mpsc::channel(1); let (tick_tx, tick_rx) = tokio::sync::watch::channel(0); let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); let addr: SocketAddr = "[::1]:0".parse...
identifier_body
http_test.rs
#[cfg(all(feature = "metrics", feature = "rt-tokio"))] mod test { use http::header::{HeaderValue, AUTHORIZATION, USER_AGENT}; use hyper::{ body, service::{make_service_fn, service_fn}, Body, Method, Request, Response, Server, }; use opentelemetry::{global, Key, KeyValue}; use...
() { let (addr_tx, addr_rx) = tokio::sync::oneshot::channel(); let (req_tx, mut req_rx) = tokio::sync::mpsc::channel(1); let (tick_tx, tick_rx) = tokio::sync::watch::channel(0); let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); let addr: SocketAddr = "[::1]:0".pa...
integration_test
identifier_name
http_test.rs
#[cfg(all(feature = "metrics", feature = "rt-tokio"))] mod test { use http::header::{HeaderValue, AUTHORIZATION, USER_AGENT}; use hyper::{ body, service::{make_service_fn, service_fn}, Body, Method, Request, Response, Server, }; use opentelemetry::{global, Key, KeyValue}; use...
} })) } }); let server = Server::bind(&addr).http1_only(true).serve(make_svc); addr_tx.send(server.local_addr()).unwrap(); println!( "Starting http server on port {}", server.l...
{ req_tx.send(req).await.unwrap(); Ok::<_, hyper::Error>( Response::builder() .status(http::StatusCode::METHOD_NOT_ALLOWED) .body(Body::empt...
conditional_block
http_test.rs
#[cfg(all(feature = "metrics", feature = "rt-tokio"))] mod test { use http::header::{HeaderValue, AUTHORIZATION, USER_AGENT}; use hyper::{ body, service::{make_service_fn, service_fn}, Body, Method, Request, Response, Server, }; use opentelemetry::{global, Key, KeyValue}; use...
.status(http::StatusCode::METHOD_NOT_ALLOWED) .body(Body::empty()) .unwrap(), ) } } })) ...
Response::builder()
random_line_split
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromScriptMsg}; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::...
_ => None, } } #[allow(unsafe_code)] pub fn get_or_init_webgl_context(&self, cx: *mut JSContext, attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> { if self.context.borrow().is_none() { ...
CanvasContext::Context2d(ref context) => Some(Root::from_ref(&*context)),
random_line_split
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromScriptMsg}; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::...
, } }); let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width")); let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height")); HTMLCanvasData { ipc_renderer: ipc_re...
{ context.to_layout().get_ipc_renderer() }
conditional_block
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromScriptMsg}; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::...
(window: &Window, url: ServoUrl) -> ImageResponse { let image_cache = window.image_cache_thread(); let (response_chan, response_port) = ipc::channel().unwrap(); image_cache.request_image(url.into(), ImageCacheChan(response_chan), None); let result = response_port.recv().unwrap(); ...
request_image_from_cache
identifier_name
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromScriptMsg}; use dom::attr::Attr; use dom::bindings::cell::DOMRefCell; use dom::...
#[allow(unsafe_code)] pub fn get_or_init_webgl_context(&self, cx: *mut JSContext, attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> { if self.context.borrow().is_none() { let window = window_from_node(self);...
{ if self.context.borrow().is_none() { let window = window_from_node(self); let size = self.get_size(); let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size); *self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref...
identifier_body
optimization-fuel-1.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 optimized = (size_of::<S1>() == 4) as usize +(size_of::<S2>() == 4) as usize; assert_eq!(optimized, 1); }
main
identifier_name
optimization-fuel-1.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 ...
use std::mem::size_of; // (#55495: The --error-format is to sidestep an issue in our test harness) // compile-flags: --error-format human -Z fuel=foo=1 struct S1(u8, u16, u8); struct S2(u8, u16, u8); fn main() { let optimized = (size_of::<S1>() == 4) as usize +(size_of::<S2>() == 4) as usize; assert...
#![crate_name="foo"]
random_line_split
install.rs
use serde::{Serialize, Serializer}; use std::str::FromStr; use datatype::Error; /// The installation outcome from a package manager. pub struct InstallOutcome { code: InstallCode, stdout: String, stderr: String, } impl InstallOutcome { /// Create a new installation outcome. pub fn new(code: In...
{ pub update_id: String, pub operation_results: Vec<InstallResult> } impl InstallReport { /// Create a new report from a list of installation results. pub fn new(update_id: String, operation_results: Vec<InstallResult>) -> Self { InstallReport { update_id, operation_results } } } ...
InstallReport
identifier_name
install.rs
use serde::{Serialize, Serializer}; use std::str::FromStr; use datatype::Error; /// The installation outcome from a package manager. pub struct InstallOutcome { code: InstallCode, stdout: String, stderr: String, } impl InstallOutcome { /// Create a new installation outcome. pub fn new(code: In...
pub package_id: String, pub name: String, pub description: String, pub last_modified: u64 } /// An encodable list of packages and firmwares to send to RVI. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)] pub struct InstalledSoftware { pub packages: Vec<Install...
/// Encapsulates a single package installed on the device. #[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)] pub struct InstalledPackage {
random_line_split
install.rs
use serde::{Serialize, Serializer}; use std::str::FromStr; use datatype::Error; /// The installation outcome from a package manager. pub struct InstallOutcome { code: InstallCode, stdout: String, stderr: String, } impl InstallOutcome { /// Create a new installation outcome. pub fn new(code: In...
/// Convert an `InstallOutcome` into a `InstallResult pub fn into_result(self, id: String) -> InstallResult { InstallResult::new(id, self.code, format!("stdout: {}\nstderr: {}\n", self.stdout, self.stderr)) } } /// An encodable response of the installation outcome. #[derive(Serialize, Deserializ...
{ Self::new(InstallCode::GENERAL_ERROR, "".into(), stderr) }
identifier_body
download.rs
// Copyright (c) 2017 Jason White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, d...
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. use std::fmt; use std::io; use std::path::{Path, PathBuf}; use std::time; use reqwest; use serde::{Deserialize, Serialize}; use tempfile::Named...
random_line_split
download.rs
// Copyright (c) 2017 Jason White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, d...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.url) } } impl fmt::Debug for Download { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.url) } } impl Task for Download { fn execute( &self, root: &Path, ...
fmt
identifier_name
download.rs
// Copyright (c) 2017 Jason White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, d...
temp.persist(&path)?; Ok(Detected::new()) } fn known_outputs(&self, resources: &mut res::Set) { // TODO: Depend on output directory. resources.insert(self.path.clone().into()); } }
{ let result: Result<(), Error> = Err(ShaVerifyError::new(self.sha256.clone(), sha256).into()); result.context(format!( "Failed to verify SHA256 for URL {}", self.url ))?; }
conditional_block
download.rs
// Copyright (c) 2017 Jason White // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, d...
}
{ // TODO: Depend on output directory. resources.insert(self.path.clone().into()); }
identifier_body
io.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 ...
(&self) -> RawSocket { *self.as_inner().socket().as_inner() } } #[stable(feature = "rust1", since = "1.0.0")] impl AsRawSocket for net::TcpListener { fn as_raw_socket(&self) -> RawSocket { *self.as_inner().socket().as_inner() } } #[stable(feature = "rust1", since = "1.0.0")] impl AsRawSocket...
as_raw_socket
identifier_name
io.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 ...
} #[stable(feature = "from_raw_os", since = "1.1.0")] impl FromRawHandle for fs::File { unsafe fn from_raw_handle(handle: RawHandle) -> fs::File { let handle = handle as ::libc::HANDLE; fs::File::from_inner(sys::fs::File::from_inner(handle)) } } /// Extract raw sockets. #[stable(feature = "ru...
{ self.as_inner().handle().raw() as RawHandle }
identifier_body
io.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
// except according to those terms. #![stable(feature = "rust1", since = "1.0.0")] use fs; use os::windows::raw; use net; use sys_common::{self, AsInner, FromInner}; use sys; /// Raw HANDLEs. #[stable(feature = "rust1", since = "1.0.0")] pub type RawHandle = raw::HANDLE; /// Raw SOCKETs. #[stable(feature = "rust1",...
// 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
hud.rs
use std::result; use toml; use sdl2::rect::Rect; #[derive(Debug)] pub enum
{ SymbolNotFound, InvalidSpec, } pub type HudResult<T> = result::Result<T, HudError>; pub struct Hud { pub health: Rect, pub speed: Rect, pub engine: Rect, pub tyres: Rect, pub armour: Rect, pub letter: Rect, pub money: Rect, } impl Hud { fn get_rect(symbol_table: &toml::va...
HudError
identifier_name
hud.rs
use std::result; use toml; use sdl2::rect::Rect; #[derive(Debug)] pub enum HudError { SymbolNotFound, InvalidSpec, } pub type HudResult<T> = result::Result<T, HudError>; pub struct Hud { pub health: Rect, pub speed: Rect, pub engine: Rect, pub tyres: Rect, pub armour: Rect, pub lette...
Ok(Rect::new(x * width, y * height, width as u32, height as u32)) } pub fn new(table: toml::value::Table) -> HudResult<Self> { let symbol_width = table.get("symbol_width").ok_or(HudError::InvalidSpec)? .as_integer().ok_or(HudError::InvalidSpec)? as i32; let symbol_height = ta...
as_integer().ok_or(HudError::InvalidSpec)? as i32;
random_line_split
add_member.rs
use std::collections::HashMap; use crate::internal::prelude::*; use crate::model::id::RoleId; /// A builder to add parameters when using [`GuildId::add_member`]. /// /// [`GuildId::add_member`]: crate::model::id::GuildId::add_member #[derive(Clone, Debug, Default)] pub struct AddMember(pub HashMap<&'static str, Value...
(&mut self, deafen: bool) -> &mut Self { self.0.insert("deaf", Value::Bool(deafen)); self } }
deafen
identifier_name
add_member.rs
use std::collections::HashMap; use crate::internal::prelude::*; use crate::model::id::RoleId; /// A builder to add parameters when using [`GuildId::add_member`]. /// /// [`GuildId::add_member`]: crate::model::id::GuildId::add_member #[derive(Clone, Debug, Default)] pub struct AddMember(pub HashMap<&'static str, Value...
/// /// [Mute Members]: crate::model::permissions::Permissions::MUTE_MEMBERS pub fn mute(&mut self, mute: bool) -> &mut Self { self.0.insert("mute", Value::Bool(mute)); self } /// Whether to deafen the member. /// /// Requires the [Deafen Members] permission. /// ///...
/// Requires the [Mute Members] permission.
random_line_split
pat-at-same-name-both.rs
// Test that `binding @ subpat` acts as a product context with respect to duplicate binding names. // The code that is tested here lives in resolve (see `resolve_pattern_inner`). fn main() { fn
(a @ a @ a: ()) {} //~^ ERROR identifier `a` is bound more than once in this parameter list //~| ERROR identifier `a` is bound more than once in this parameter list match Ok(0) { Ok(a @ b @ a) //~^ ERROR identifier `a` is bound more than once in the same pattern | Err(a @ b @ a) ...
f
identifier_name
pat-at-same-name-both.rs
// Test that `binding @ subpat` acts as a product context with respect to duplicate binding names. // The code that is tested here lives in resolve (see `resolve_pattern_inner`). fn main() { fn f(a @ a @ a: ()) {} //~^ ERROR identifier `a` is bound more than once in this parameter list //~| ERROR identifi...
//~| ERROR identifier `a` is bound more than once in the same pattern let ref a @ ref a = (); //~^ ERROR identifier `a` is bound more than once in the same pattern let ref mut a @ ref mut a = (); //~^ ERROR identifier `a` is bound more than once in the same pattern let a @ (Ok(a) | Err(a)) = Ok...
//~^ ERROR identifier `a` is bound more than once in the same pattern
random_line_split
pat-at-same-name-both.rs
// Test that `binding @ subpat` acts as a product context with respect to duplicate binding names. // The code that is tested here lives in resolve (see `resolve_pattern_inner`). fn main() { fn f(a @ a @ a: ()) {} //~^ ERROR identifier `a` is bound more than once in this parameter list //~| ERROR identifi...
} let a @ a @ a = (); //~^ ERROR identifier `a` is bound more than once in the same pattern //~| ERROR identifier `a` is bound more than once in the same pattern let ref a @ ref a = (); //~^ ERROR identifier `a` is bound more than once in the same pattern let ref mut a @ ref mut a = (); ...
{}
conditional_block
pat-at-same-name-both.rs
// Test that `binding @ subpat` acts as a product context with respect to duplicate binding names. // The code that is tested here lives in resolve (see `resolve_pattern_inner`). fn main() { fn f(a @ a @ a: ())
//~^ ERROR identifier `a` is bound more than once in this parameter list //~| ERROR identifier `a` is bound more than once in this parameter list match Ok(0) { Ok(a @ b @ a) //~^ ERROR identifier `a` is bound more than once in the same pattern | Err(a @ b @ a) //~^ ERROR id...
{}
identifier_body
mod.rs
use super::i3::*; use std::borrow::Cow; mod clock; mod shell; mod florp_blarg; pub use self::clock::*; pub use self::shell::*; pub use self::florp_blarg::*; /// A type that produces blocks of data. /// BlockProducer can respond to mouse-events. pub trait Widget { /// Updates the state of the producer and returns...
} impl<T: Into<String> + Clone + Send +'static> Widget for T { fn update(&mut self) -> Cow<'static, Block> { Cow::Owned(Block { full_text: self.clone().into(), ..Block::default() }) } }
{ Cow::Borrowed(self) }
identifier_body
mod.rs
use super::i3::*; use std::borrow::Cow; mod clock; mod shell; mod florp_blarg; pub use self::clock::*; pub use self::shell::*; pub use self::florp_blarg::*; /// A type that produces blocks of data. /// BlockProducer can respond to mouse-events. pub trait Widget { /// Updates the state of the producer and returns...
<'a>(&'a mut self) -> Cow<'a, Block> { Cow::Borrowed(self) } } impl<T: Into<String> + Clone + Send +'static> Widget for T { fn update(&mut self) -> Cow<'static, Block> { Cow::Owned(Block { full_text: self.clone().into(), ..Block::default() }) } }
update
identifier_name
mod.rs
use super::i3::*; use std::borrow::Cow; mod clock; mod shell; mod florp_blarg;
/// A type that produces blocks of data. /// BlockProducer can respond to mouse-events. pub trait Widget { /// Updates the state of the producer and returns the new block data. fn update<'a>(&'a mut self) -> Cow<'a, Block>; /// Gets the name of the block, if available. fn get_name(&self) -> Option<&st...
pub use self::clock::*; pub use self::shell::*; pub use self::florp_blarg::*;
random_line_split
test_all_types.rs
#![no_main] extern crate libfuzzer_sys; extern crate capnp; use capnp::{serialize, message}; use test_capnp::test_all_types; pub mod test_capnp; fn traverse(v: test_all_types::Reader) -> ::capnp::Result<()> { v.get_int64_field(); v.get_float32_field(); v.get_float64_field(); v.get_text_field()?; ...
list.set_with_caveats(0, root)?; list.set_with_caveats(1, root)?; } traverse(root_builder.into_reader())?; } // init_root() will zero the previous value let mut new_root = message.init_root::<test_all_types::Builder>(); new_root.set_struct_field(root)?; O...
{ let orig_data = data; let message_reader = serialize::read_message( &mut data, *message::ReaderOptions::new().traversal_limit_in_words(4 * 1024))?; assert!(orig_data.len() > data.len()); let root: test_all_types::Reader = try!(message_reader.get_root()); root.total_size()?; tr...
identifier_body
test_all_types.rs
#![no_main] extern crate libfuzzer_sys; extern crate capnp; use capnp::{serialize, message}; use test_capnp::test_all_types; pub mod test_capnp; fn traverse(v: test_all_types::Reader) -> ::capnp::Result<()> { v.get_int64_field(); v.get_float32_field(); v.get_float64_field(); v.get_text_field()?; ...
traverse(root_builder.into_reader())?; } // init_root() will zero the previous value let mut new_root = message.init_root::<test_all_types::Builder>(); new_root.set_struct_field(root)?; Ok(()) } #[export_name="rust_fuzzer_test_input"] pub extern fn go(data: &[u8]) { let _ = try_go(dat...
random_line_split
test_all_types.rs
#![no_main] extern crate libfuzzer_sys; extern crate capnp; use capnp::{serialize, message}; use test_capnp::test_all_types; pub mod test_capnp; fn traverse(v: test_all_types::Reader) -> ::capnp::Result<()> { v.get_int64_field(); v.get_float32_field(); v.get_float64_field(); v.get_text_field()?; ...
(data: &[u8]) { let _ = try_go(data); }
go
identifier_name
mod.rs
// Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: //
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial ...
// Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights
random_line_split
htmltablesectionelement.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::RGBA; use dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{self, HTMLTableSection...
(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLTableSectionElement> { Node::reflect_node(Box::new(HTMLTableSectionElement::new_inherited(local_name, prefix, document)), document, HTMLTableSectionElementBind...
new
identifier_name
htmltablesectionelement.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
use cssparser::RGBA; use dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{self, HTMLTableSectionElementMethods}; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::error::{ErrorResult, Fallible}; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRo...
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
random_line_split
htmltablesectionelement.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::RGBA; use dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{self, HTMLTableSection...
// https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow fn InsertRow(&self, index: i32) -> Fallible<DomRoot<HTMLElement>> { let node = self.upcast::<Node>(); node.insert_cell_or_row( index, || self.Rows(), || HTMLTableRowElement::new(local_name!("tr")...
{ HTMLCollection::create(&window_from_node(self), self.upcast(), Box::new(RowsFilter)) }
identifier_body
test_interop_data.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
} } } } if errors.is_empty() { Ok(()) } else { panic!( "There were errors reading some.avro files:\n{}", errors.join(", ") ); } } fn test_user_metadata<R: Read>( reader: &Reader<BufReader<R>>, expected_user_me...
{ errors.push(format!( "There is a problem with reading of '{:?}', \n {:?}\n", &path, e )); }
conditional_block
test_interop_data.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
let reader = Reader::new(BufReader::new(&content))?; test_user_metadata(&reader, &expected_user_metadata); for value in reader { if let Err(e) = value { errors.push(format!( "There is a problem with...
{ let mut expected_user_metadata: HashMap<String, Vec<u8>> = HashMap::new(); expected_user_metadata.insert("user_metadata".to_string(), b"someByteArray".to_vec()); let data_dir = std::fs::read_dir("../../build/interop/data/") .expect("Unable to list the interop data directory"); let mut errors...
identifier_body
test_interop_data.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may...
() -> anyhow::Result<()> { let mut expected_user_metadata: HashMap<String, Vec<u8>> = HashMap::new(); expected_user_metadata.insert("user_metadata".to_string(), b"someByteArray".to_vec()); let data_dir = std::fs::read_dir("../../build/interop/data/") .expect("Unable to list the interop data director...
main
identifier_name
test_interop_data.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS,...
random_line_split
day24.rs
#[macro_use] extern crate clap; use clap::App; extern crate regex; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::collections::HashSet; fn main() { let yaml = load_yaml!("cli.yml"); let matches = App::from_yaml(yaml).get_matches(); let filename = matches.value_of("FILE").unwr...
fn parse_input(input : Vec<&str>) -> Vec<i32> { let mut v = Vec::new(); for s in input { if s.trim().len() > 0 { v.push(s.parse::<i32>().unwrap()); } } v.sort_by(|a,b| b.cmp(a)); v }
}
random_line_split
day24.rs
#[macro_use] extern crate clap; use clap::App; extern crate regex; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::collections::HashSet; fn main() { let yaml = load_yaml!("cli.yml"); let matches = App::from_yaml(yaml).get_matches(); let filename = matches.value_of("FILE").unwr...
let qe : usize = a.iter().fold(1, |qe, x| qe * *x as usize); min_qe = std::cmp::min(qe, min_qe); } } println!("Part 1: Min QE = {}", min_qe); } fn sum_exists(packages : &Vec<i32>, target : i32) -> bool { let mut exists = false; for (i,p) in packages.iter().enumerate() ...
{ let mut all : HashSet<Vec<i32>> = HashSet::new(); let mut min_length = std::usize::MAX; let groupings = generate_sum(&packages, target, Vec::new()); for g in groupings { if g.len() <= min_length { let available_packages = packages.clone().into_iter().filter(|x| !g.contains(x)).c...
identifier_body
day24.rs
#[macro_use] extern crate clap; use clap::App; extern crate regex; use std::error::Error; use std::fs::File; use std::io::prelude::*; use std::collections::HashSet; fn main() { let yaml = load_yaml!("cli.yml"); let matches = App::from_yaml(yaml).get_matches(); let filename = matches.value_of("FILE").unwr...
(packages : &Vec<i32>, target : i32) -> bool { let mut exists = false; for (i,p) in packages.iter().enumerate() { if target - p == 0 { exists = true; } else if target - p > 0{ let new_vec = packages[i+1..packages.len()].to_vec(); exists = sum_exis...
sum_exists
identifier_name
ed25519.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module provides an API for the PureEdDSA signature scheme over the ed25519 twisted //! Edwards curve as defined in [RFC8032](https://tools.ietf.org/html/rfc8032). //! //! Signature verification also checks and rejects non-canon...
<T: CryptoHash + Serialize>(&self, message: &T) -> Ed25519Signature { let mut bytes = <T::Hasher as CryptoHasher>::seed().to_vec(); bcs::serialize_into(&mut bytes, &message) .map_err(|_| CryptoMaterialError::SerializationError) .expect("Serialization of signable material should not...
sign
identifier_name
ed25519.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module provides an API for the PureEdDSA signature scheme over the ed25519 twisted //! Edwards curve as defined in [RFC8032](https://tools.ietf.org/html/rfc8032). //! //! Signature verification also checks and rejects non-canon...
/// - `x25519_bytes`: bit representation of a public key in clamped /// Montgomery form, a.k.a. the x25519 public key format. /// - `negative`: whether to interpret the given point as a negative point, /// as the Montgomery form erases the sign byte. By XEdDSA /// ...
/// /// Arguments:
random_line_split
ed25519.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 //! This module provides an API for the PureEdDSA signature scheme over the ed25519 twisted //! Edwards curve as defined in [RFC8032](https://tools.ietf.org/html/rfc8032). //! //! Signature verification also checks and rejects non-canon...
} /// Check if S < L to capture invalid signatures. fn check_s_lt_l(s: &[u8]) -> bool { for i in (0..32).rev() { match s[i].cmp(&L[i]) { Ordering::Less => return true, Ordering::Greater => return false, _ => {} } } // As this stage S == L which implies a ...
write!(f, "Ed25519Signature({})", self) }
identifier_body
of.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::any::Any; use core::any::TypeId; // #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub struct TypeId { // t: u64, // } // impl TypeId { // /// Re...
; let x: T = 68; let x_typeid: TypeId = x.get_type_id(); let typeid: TypeId = TypeId::of::<A>(); assert_eq!(x_typeid, typeid); } }
A
identifier_name
of.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::any::Any; use core::any::TypeId; // #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub struct TypeId { // t: u64, // } // impl TypeId { // /// Re...
struct A; let x: T = 68; let x_typeid: TypeId = x.get_type_id(); let typeid: TypeId = TypeId::of::<A>(); assert_eq!(x_typeid, typeid); } }
} #[test] #[should_panic] fn of_test2() {
random_line_split
of.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { use core::any::Any; use core::any::TypeId; // #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] // #[stable(feature = "rust1", since = "1.0.0")] // pub struct TypeId { // t: u64, // } // impl TypeId { // /// Re...
#[test] #[should_panic] fn of_test2() { struct A; let x: T = 68; let x_typeid: TypeId = x.get_type_id(); let typeid: TypeId = TypeId::of::<A>(); assert_eq!(x_typeid, typeid); } }
{ let x: T = 68; let x_typeid: TypeId = x.get_type_id(); let typeid: TypeId = TypeId::of::<T>(); assert_eq!(x_typeid, typeid); }
identifier_body
core.rs
// Copyright 2012-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-MI...
} pub struct CrateAnalysis { pub exported_items: privacy::ExportedItems, pub public_items: privacy::PublicItems, pub external_paths: ExternalPaths, } /// Parses, resolves, and typechecks the given crate fn get_ast_and_resolve(cpath: &Path, libs: HashSet<Path>, cfgs: Vec<StrBuf>) ->...
{ match self.maybe_typed { Typed(ref tcx) => &tcx.sess, NotTyped(ref sess) => sess } }
identifier_body
core.rs
// 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 rustc; use rust...
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
random_line_split
core.rs
// Copyright 2012-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-MI...
{ pub krate: ast::Crate, pub maybe_typed: MaybeTyped, pub src: Path, pub external_paths: ExternalPaths, } impl DocContext { pub fn sess<'a>(&'a self) -> &'a driver::session::Session { match self.maybe_typed { Typed(ref tcx) => &tcx.sess, NotTyped(ref sess) => sess ...
DocContext
identifier_name
unit.rs
type Health = f64; type Attack = f64; type Level = u8; type Experience = f64; pub trait Unit { fn new(health: f64, attack: f64) -> Self; fn realize_hp(&self) -> f64; fn realize_atk(&self) -> f64; fn change_current_hp(&mut self, amount: f64); fn show(&self) -> String { format!("{}hp {}atk", ...
(&self) -> f64 { self.hp } fn realize_atk(&self) -> f64 { self.atk } fn change_current_hp(&mut self, amount: f64) { self.hp += amount; } }
realize_hp
identifier_name
unit.rs
type Health = f64; type Attack = f64; type Level = u8; type Experience = f64; pub trait Unit { fn new(health: f64, attack: f64) -> Self; fn realize_hp(&self) -> f64; fn realize_atk(&self) -> f64; fn change_current_hp(&mut self, amount: f64); fn show(&self) -> String { format!("{}hp {}atk", ...
fn realize_hp(&self) -> f64 { self.hp } fn realize_atk(&self) -> f64 { self.atk } fn change_current_hp(&mut self, amount: f64) { self.hp += amount; } } impl Hero { pub fn realize_lvl(&self) -> u8 { self.lvl } pub fn realize_exp(&self) -> f64 { self.exp } } #[derive(Clone)] pub struct NonHero { ...
}
random_line_split
unit.rs
type Health = f64; type Attack = f64; type Level = u8; type Experience = f64; pub trait Unit { fn new(health: f64, attack: f64) -> Self; fn realize_hp(&self) -> f64; fn realize_atk(&self) -> f64; fn change_current_hp(&mut self, amount: f64); fn show(&self) -> String { format!("{}hp {}atk", ...
fn change_current_hp(&mut self, amount: f64) { self.hp += amount; } }
{ self.atk }
identifier_body
lib.rs
#![doc(html_root_url = "http://cpjreynolds.github.io/rustty/rustty/index.html")] //! # Rustty //! //! Rustty is a terminal UI library that provides a simple, concise abstraction over an //! underlying terminal device. //! //! Rustty is based on the concepts of cells and events. A terminal display is an array of cells,...
pub use core::terminal::Terminal; pub use core::cellbuffer::{Cell, Color, Attr, CellAccessor}; pub use core::position::{Pos, Size, HasSize, HasPosition}; pub use core::input::Event;
random_line_split
gzip.rs
use byteorder::{LittleEndian, WriteBytesExt}; use std::io::{self, Write}; use crate::deflate::{deflate, BlockType}; use crate::Options; const CRC_IEEE: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC); static HEADER: &'static [u8] = &[ 31, // ID1 139, // ID2
0, // FLG 0, // MTIME 0, 0, 0, 2, // XFL, 2 indicates best compression. 3, // OS follows Unix conventions. ]; /// Compresses the data according to the gzip specification, RFC 1952. pub fn gzip_compress<W>(options: &Options, in_data: &[u8], mut out: W) -> io::Result<()> where W: Write, { out...
8, // CM
random_line_split
gzip.rs
use byteorder::{LittleEndian, WriteBytesExt}; use std::io::{self, Write}; use crate::deflate::{deflate, BlockType}; use crate::Options; const CRC_IEEE: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC); static HEADER: &'static [u8] = &[ 31, // ID1 139, // ID2 8, // CM 0, // FLG 0, ...
{ out.by_ref().write_all(HEADER)?; deflate(options, BlockType::Dynamic, in_data, out.by_ref())?; out.by_ref() .write_u32::<LittleEndian>(CRC_IEEE.checksum(in_data))?; out.write_u32::<LittleEndian>(in_data.len() as u32) }
identifier_body
gzip.rs
use byteorder::{LittleEndian, WriteBytesExt}; use std::io::{self, Write}; use crate::deflate::{deflate, BlockType}; use crate::Options; const CRC_IEEE: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC); static HEADER: &'static [u8] = &[ 31, // ID1 139, // ID2 8, // CM 0, // FLG 0, ...
<W>(options: &Options, in_data: &[u8], mut out: W) -> io::Result<()> where W: Write, { out.by_ref().write_all(HEADER)?; deflate(options, BlockType::Dynamic, in_data, out.by_ref())?; out.by_ref() .write_u32::<LittleEndian>(CRC_IEEE.checksum(in_data))?; out.write_u32::<LittleEndian>(in_data.l...
gzip_compress
identifier_name
vga_buffer.rs
use core::ptr::Unique; use core::fmt::Write; use spin::Mutex; macro_rules! print { ($($arg:tt)*) => ({ use core::fmt::Write; $crate::vga_buffer::WRITER.lock().write_fmt(format_args!($($arg)*)).unwrap(); }); } macro_rules! println { ($fmt:expr) => (print!(concat!($fmt, "\n"))); ($fmt:ex...
} pub fn write_str(&mut self, s: &str) { for byte in s.bytes() { self.write_byte(byte) } } fn buffer(&mut self) -> &mut Buffer { unsafe { self.buffer.get_mut() } } fn new_line(&mut self) { for row in 0..(BUFFER_HEIGHT-1) { let buffer = ...
{ match byte { b'\n' => { self.new_line(); }, byte => { if self.column_position >= BUFFER_WIDTH { self.new_line(); } let row = BUFFER_HEIGHT -1; let col = self.column_position...
identifier_body
vga_buffer.rs
use core::ptr::Unique; use core::fmt::Write; use spin::Mutex; macro_rules! print { ($($arg:tt)*) => ({ use core::fmt::Write; $crate::vga_buffer::WRITER.lock().write_fmt(format_args!($($arg)*)).unwrap(); }); } macro_rules! println { ($fmt:expr) => (print!(concat!($fmt, "\n"))); ($fmt:ex...
, byte => { if self.column_position >= BUFFER_WIDTH { self.new_line(); } let row = BUFFER_HEIGHT -1; let col = self.column_position; self.buffer().chars[row][col] = ScreenChar { ascii_ch...
{ self.new_line(); }
conditional_block
vga_buffer.rs
use core::ptr::Unique; use core::fmt::Write; use spin::Mutex; macro_rules! print { ($($arg:tt)*) => ({ use core::fmt::Write; $crate::vga_buffer::WRITER.lock().write_fmt(format_args!($($arg)*)).unwrap(); }); } macro_rules! println { ($fmt:expr) => (print!(concat!($fmt, "\n"))); ($fmt:ex...
{ Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magenta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagenta = 13, Yellow = ...
Color
identifier_name
vga_buffer.rs
use core::ptr::Unique; use core::fmt::Write; use spin::Mutex; macro_rules! print { ($($arg:tt)*) => ({ use core::fmt::Write; $crate::vga_buffer::WRITER.lock().write_fmt(format_args!($($arg)*)).unwrap(); }); } macro_rules! println { ($fmt:expr) => (print!(concat!($fmt, "\n"))); ($fmt:ex...
for byte in s.bytes() { self.write_byte(byte) } } fn buffer(&mut self) -> &mut Buffer { unsafe { self.buffer.get_mut() } } fn new_line(&mut self) { for row in 0..(BUFFER_HEIGHT-1) { let buffer = self.buffer(); buffer.chars[row] = buff...
random_line_split
maildir.rs
use std::time::Duration; use chan::Sender; use block::{Block, ConfigBlock}; use config::Config; use de::deserialize_duration; use errors::*; use widgets::text::TextWidget; use widget::{I3BarWidget, State}; use input::I3BarEvent; use scheduler::Task; use maildir::Maildir as ExtMaildir; use uuid::Uuid; pub struct Mail...
self.text.set_state(state); self.text.set_text(format!("{}", newmails)); Ok(Some(self.update_interval)) } fn view(&self) -> Vec<&I3BarWidget> { vec![&self.text] } fn click(&mut self, _: &I3BarEvent) -> Result<()> { Ok(()) } fn id(&self) -> &str { ...
{ state = { State::Warning }; }
conditional_block