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
person.rs
use std::time; use time::Tm; use mre::model::{Model, Error}; // Create a class to act as our model. Unfortunately Rust's classes aren't // finished yet, and are missing a couple features that would help clean up // models. First, there's no way to mix in implementation of functions, so we // need to duplicate some cod...
(es: elasticsearch::Client) -> ~[Person] { // This query can be a little complicated for those who have never used // elasticsearch. All it says is that we want to fetch 50 documents on the // index "helloeveryone" and the type "person", sorted by time. do mre::model::search(es) |bld| { bld ...
last_50
identifier_name
reflector.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 syntax::ext::base::ExtCtxt; use syntax::codemap::Span; use syntax::ptr::P; use syntax::ast::{Item, MetaItem}; ...
let impl_item = quote_item!(cx, impl ::dom::bindings::utils::Reflectable for $struct_name { fn reflector<'a>(&'a self) -> &'a ::dom::bindings::utils::Reflector { self.$field_name.reflector() } ...
{ if let ast::ItemStruct(ref def, _) = item.node { let struct_name = item.ident; // This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time match def.fields.iter().find(|f| match_ty_unwrap(&*f.node.ty, &["dom", "bindings", "utils", "Reflector"]).is_some()...
identifier_body
reflector.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 syntax::ext::base::ExtCtxt; use syntax::codemap::Span; use syntax::ptr::P; use syntax::ast::{Item, MetaItem}; ...
(cx: &mut ExtCtxt, span: Span, _: &MetaItem, item: &Item, push: |P<Item>|) { if let ast::ItemStruct(ref def, _) = item.node { let struct_name = item.ident; // This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time match def.fields.iter().find(|f| match_t...
expand_reflector
identifier_name
reflector.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 syntax::ext::base::ExtCtxt; use syntax::codemap::Span; use syntax::ptr::P; use syntax::ast::{Item, MetaItem}; ...
} } ); impl_item.map(|it| push(it)) } }; } else { cx.span_err(span, "#[dom_struct] seems to have been applied to a non-struct"); } }
self.$field_name.reflector()
random_line_split
reflector.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 syntax::ext::base::ExtCtxt; use syntax::codemap::Span; use syntax::ptr::P; use syntax::ast::{Item, MetaItem}; ...
impl ::dom::bindings::utils::Reflectable for $struct_name { fn reflector<'a>(&'a self) -> &'a ::dom::bindings::utils::Reflector { self.$field_name.reflector() } } ); impl_i...
{ let struct_name = item.ident; // This path has to be hardcoded, unfortunately, since we can't resolve paths at expansion time match def.fields.iter().find(|f| match_ty_unwrap(&*f.node.ty, &["dom", "bindings", "utils", "Reflector"]).is_some()) { // If it has a field that is a Reflec...
conditional_block
angle.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 glutin; use glutin::{WindowBuilder, ContextBuilder, EventsLoop, Window, CreationError}; #[cfg(not(windows))] ...
#[cfg(windows)] pub fn with_window( window_builder: WindowBuilder, context_builder: ContextBuilder, events_loop: &EventsLoop, ) -> Result<(Window, Self), CreationError> { use glutin::os::windows::WindowExt; // FIXME: &context_builder.pf_reqs https://github.com/tom...
{ Err(CreationError::PlatformSpecific("ANGLE rendering is only supported on Windows".into())) }
identifier_body
angle.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 glutin; use glutin::{WindowBuilder, ContextBuilder, EventsLoop, Window, CreationError}; #[cfg(not(windows))] ...
( _: WindowBuilder, _: ContextBuilder, _: &EventsLoop, ) -> Result<(Window, Self), CreationError> { Err(CreationError::PlatformSpecific("ANGLE rendering is only supported on Windows".into())) } #[cfg(windows)] pub fn with_window( window_builder: WindowBuilder, ...
with_window
identifier_name
angle.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 glutin; use glutin::{WindowBuilder, ContextBuilder, EventsLoop, Window, CreationError}; #[cfg(not(windows))] ...
events_loop: &EventsLoop, ) -> Result<(Window, Self), CreationError> { use glutin::os::windows::WindowExt; // FIXME: &context_builder.pf_reqs https://github.com/tomaka/glutin/pull/1002 let pf_reqs = &glutin::PixelFormatRequirements::default(); let gl_attr = &context_builder...
pub fn with_window( window_builder: WindowBuilder, context_builder: ContextBuilder,
random_line_split
errors.rs
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use { proc_macro2::{Span, TokenStream}, quote::ToTokens, std::cell::RefCell, }; /// A type for collecting procedural macro errors. #[derive(Default)...
/// Error on literals, expecting attribute syntax. pub fn expect_nested_meta<'a>(&self, nm: &'a syn::NestedMeta) -> Option<&'a syn::Meta> { match nm { syn::NestedMeta::Lit(l) => { self.err(l, "Unexpected literal"); None } syn::NestedM...
{ self.err_span(second, &["Duplicate ", attr_kind, " attribute"].concat()); self.err_span(first, &["First ", attr_kind, " attribute here"].concat()); }
identifier_body
errors.rs
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use { proc_macro2::{Span, TokenStream}, quote::ToTokens, std::cell::RefCell, }; /// A type for collecting procedural macro errors. #[derive(Default)...
(&self, span: Span, msg: &str) { self.push(syn::Error::new(span, msg)); } /// Push a `syn::Error` onto the list of errors to issue. pub fn push(&self, err: syn::Error) { self.errors.borrow_mut().push(err); } } impl ToTokens for Errors { /// Convert the errors into tokens that, when...
err_span
identifier_name
errors.rs
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use { proc_macro2::{Span, TokenStream}, quote::ToTokens, std::cell::RefCell, }; /// A type for collecting procedural macro errors. #[derive(Default)...
/// Push a `syn::Error` onto the list of errors to issue. pub fn push(&self, err: syn::Error) { self.errors.borrow_mut().push(err); } } impl ToTokens for Errors { /// Convert the errors into tokens that, when emit, will cause /// the user of the macro to receive compiler errors. fn to_t...
pub fn err_span(&self, span: Span, msg: &str) { self.push(syn::Error::new(span, msg)); }
random_line_split
dead_code.rs
use ast::cfg::{Block, BlockEnd, BlockId, BlockLink, Function, Instruction, Program}; use plank_syntax::position::Spanned; use std::collections::{HashSet, VecDeque}; use CompileCtx; fn function_block_chain(f: &Function) -> VecDeque<BlockId> { let mut blocks = VecDeque::new(); let mut current = if let Some(block...
.span(span) .build(); } fn can_be_dead(block: &Block) -> bool { for op in &block.ops { match **op { Instruction::Drop(_) => {} _ => return true, } } false } fn analyze_function(f: &mut Function, ctx: &mut CompileCtx) { let mut blocks = function_blo...
} ctx.reporter .warning("dead code detected", span)
random_line_split
dead_code.rs
use ast::cfg::{Block, BlockEnd, BlockId, BlockLink, Function, Instruction, Program}; use plank_syntax::position::Spanned; use std::collections::{HashSet, VecDeque}; use CompileCtx; fn function_block_chain(f: &Function) -> VecDeque<BlockId> { let mut blocks = VecDeque::new(); let mut current = if let Some(block...
fn can_be_dead(block: &Block) -> bool { for op in &block.ops { match **op { Instruction::Drop(_) => {} _ => return true, } } false } fn analyze_function(f: &mut Function, ctx: &mut CompileCtx) { let mut blocks = function_block_chain(f); debug_assert_eq!(blo...
{ let mut span = Spanned::span(&block.ops[0]); for i in &block.ops { match **i { Instruction::StartStatement => { span = Spanned::span(i); break; } _ => { span = span.merge(Spanned::span(i)); } } ...
identifier_body
dead_code.rs
use ast::cfg::{Block, BlockEnd, BlockId, BlockLink, Function, Instruction, Program}; use plank_syntax::position::Spanned; use std::collections::{HashSet, VecDeque}; use CompileCtx; fn function_block_chain(f: &Function) -> VecDeque<BlockId> { let mut blocks = VecDeque::new(); let mut current = if let Some(block...
(block: &Block, ctx: &mut CompileCtx) { let mut span = Spanned::span(&block.ops[0]); for i in &block.ops { match **i { Instruction::StartStatement => { span = Spanned::span(i); break; } _ => { span = span.merge(Spanned::...
report_unreachable
identifier_name
dead_code.rs
use ast::cfg::{Block, BlockEnd, BlockId, BlockLink, Function, Instruction, Program}; use plank_syntax::position::Spanned; use std::collections::{HashSet, VecDeque}; use CompileCtx; fn function_block_chain(f: &Function) -> VecDeque<BlockId> { let mut blocks = VecDeque::new(); let mut current = if let Some(block...
} if strong_reachable.is_none() { strong_reachable = Some(reachable.clone()); } follow_strong = true; while let Some(block) = blocks.pop_front() { if!reachable.contains(&block) && can_be_dead(&f.blocks[&block]) { report_unreachable(&f.bloc...
{ reachable.insert(block); let block = &f.blocks[&block]; match block.end { BlockEnd::Branch(_, a, b) => { queue.push_back(a); queue.push_back(b); } BlockEnd::Jump(...
conditional_block
hex.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
#[test] pub fn test_from_hex_invalid_char() { assert!("66y6".from_hex().is_err()); } #[test] pub fn test_from_hex_ignores_whitespace() { assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), b"foobar"); } #[test] pub fn test_to_hex_all_bytes() { ...
random_line_split
hex.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&self) -> &str { match *self { InvalidHexCharacter(..) => "invalid character", InvalidHexLength => "invalid length", } } } impl FromHex for str { /// Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`) /// to the byte values it encodes. /// /...
description
identifier_name
hex.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
let sb = s.as_bytes().to_hex(); b.iter(|| { sb.from_hex().unwrap(); }); b.bytes = sb.len() as u64; } }
identifier_body
lib.register_restriction.rs
// This file was generated by `cargo dev update_lints`. // Use that command to update this file and do not edit by hand. // Manual edits will be overwritten. store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![ LintId::of(arithmetic::FLOAT_ARITHMETIC), LintId::of(arithmetic::INTE...
LintId::of(methods::CLONE_ON_REF_PTR), LintId::of(methods::EXPECT_USED), LintId::of(methods::FILETYPE_IS_FILE), LintId::of(methods::GET_UNWRAP), LintId::of(methods::UNWRAP_USED), LintId::of(misc::FLOAT_CMP_CONST), LintId::of(misc_early::SEPARATED_LITERAL_SUFFIX), LintId::of(misc_early::U...
LintId::of(mem_forget::MEM_FORGET),
random_line_split
cholesky.rs
#[macro_use] extern crate linxal; extern crate ndarray; extern crate num_traits; extern crate rand; use ndarray::{Array, ArrayBase, Data, Ix2}; use rand::thread_rng; use linxal::types::{LinxalScalar, LinxalMatrix, Symmetric, c32, c64}; use linxal::types::error::{ CholeskyError}; use linxal::generate::{RandomSemiPosit...
} fn cholesky_identity_generic<T: LinxalScalar>() { for n in 1..11 { let m: Array<T, Ix2> = Array::eye(n); let l = m.cholesky(Symmetric::Upper).ok().unwrap(); assert_eq_within_tol!(l, m, 1e-5.into()); } } fn cholesky_generate_generic<T: LinxalScalar>(uplo: Symmetric) { let mut r...
{ // Check the dimension assert_eq!(mat.dim(), chol.dim()); // The matrix must be triangular assert!(chol.is_triangular(uplo, None)); // The fatorization must match the original matrix. match uplo { Symmetric::Lower => { let u = chol.conj_t(); assert_eq_within_t...
identifier_body
cholesky.rs
#[macro_use] extern crate linxal; extern crate ndarray; extern crate num_traits; extern crate rand; use ndarray::{Array, ArrayBase, Data, Ix2}; use rand::thread_rng; use linxal::types::{LinxalScalar, LinxalMatrix, Symmetric, c32, c64}; use linxal::types::error::{ CholeskyError}; use linxal::generate::{RandomSemiPosit...
assert_eq_within_tol!(l, m, 1e-5.into()); } } fn cholesky_generate_generic<T: LinxalScalar>(uplo: Symmetric) { let mut rng = thread_rng(); for n in 1..11 { let m: Array<T, Ix2> = RandomSemiPositive::new(n, &mut rng).generate().unwrap(); let res = m.cholesky(uplo); let chol ...
let l = m.cholesky(Symmetric::Upper).ok().unwrap();
random_line_split
cholesky.rs
#[macro_use] extern crate linxal; extern crate ndarray; extern crate num_traits; extern crate rand; use ndarray::{Array, ArrayBase, Data, Ix2}; use rand::thread_rng; use linxal::types::{LinxalScalar, LinxalMatrix, Symmetric, c32, c64}; use linxal::types::error::{ CholeskyError}; use linxal::generate::{RandomSemiPosit...
<T: LinxalScalar>() { for n in 1..11 { let m: Array<T, Ix2> = Array::eye(n); let l = m.cholesky(Symmetric::Upper).ok().unwrap(); assert_eq_within_tol!(l, m, 1e-5.into()); } } fn cholesky_generate_generic<T: LinxalScalar>(uplo: Symmetric) { let mut rng = thread_rng(); for n in 1...
cholesky_identity_generic
identifier_name
cholesky.rs
#[macro_use] extern crate linxal; extern crate ndarray; extern crate num_traits; extern crate rand; use ndarray::{Array, ArrayBase, Data, Ix2}; use rand::thread_rng; use linxal::types::{LinxalScalar, LinxalMatrix, Symmetric, c32, c64}; use linxal::types::error::{ CholeskyError}; use linxal::generate::{RandomSemiPosit...
} } fn cholesky_identity_generic<T: LinxalScalar>() { for n in 1..11 { let m: Array<T, Ix2> = Array::eye(n); let l = m.cholesky(Symmetric::Upper).ok().unwrap(); assert_eq_within_tol!(l, m, 1e-5.into()); } } fn cholesky_generate_generic<T: LinxalScalar>(uplo: Symmetric) { let...
{ let l = chol.conj_t(); println!("{:?} {:?} {:?} {:?}", chol, l, l.dot(chol), mat); assert_eq_within_tol!(l.dot(chol), mat, 1e-4.into()); }
conditional_block
utils.rs
#![allow(dead_code)] use std::{cmp, io}; use bytes::{BufMut, BytesMut}; pub const SIZE: usize = 31; #[derive(Serialize, Deserialize)] pub struct Message { pub message: &'static str, } pub struct Writer<'a>(pub &'a mut BytesMut); impl<'a> io::Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Res...
} b'\'' => { let _ = writer.0.put_slice(b"&#x27;"); } b'/' => { let _ = writer.0.put_slice(b"&#x2f;"); } _ => panic!("incorrect indexing"), } } } if last_po...
{ let bytes = s.as_bytes(); let mut last_pos = 0; for (idx, b) in s.as_bytes().iter().enumerate() { if escapable(*b) { let _ = writer.0.put_slice(&bytes[last_pos..idx]); last_pos = idx + 1; match *b { b'<' => { let _ = writer.0...
identifier_body
utils.rs
#![allow(dead_code)] use std::{cmp, io}; use bytes::{BufMut, BytesMut}; pub const SIZE: usize = 31; #[derive(Serialize, Deserialize)] pub struct Message {
} pub struct Writer<'a>(pub &'a mut BytesMut); impl<'a> io::Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.put_slice(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } pub fn get_query_param(query: &str) -> u16 { ...
pub message: &'static str,
random_line_split
utils.rs
#![allow(dead_code)] use std::{cmp, io}; use bytes::{BufMut, BytesMut}; pub const SIZE: usize = 31; #[derive(Serialize, Deserialize)] pub struct Message { pub message: &'static str, } pub struct Writer<'a>(pub &'a mut BytesMut); impl<'a> io::Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Res...
b'&' => { let _ = writer.0.put_slice(b"&amp;"); } b'"' => { let _ = writer.0.put_slice(b"&quot;"); } b'\'' => { let _ = writer.0.put_slice(b"&#x27;"); } ...
{ let _ = writer.0.put_slice(b"&gt;"); }
conditional_block
utils.rs
#![allow(dead_code)] use std::{cmp, io}; use bytes::{BufMut, BytesMut}; pub const SIZE: usize = 31; #[derive(Serialize, Deserialize)] pub struct Message { pub message: &'static str, } pub struct Writer<'a>(pub &'a mut BytesMut); impl<'a> io::Write for Writer<'a> { fn
(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.put_slice(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } pub fn get_query_param(query: &str) -> u16 { let q = if let Some(pos) = query.find("q") { query.split_at(pos + 2).1.parse::<u16>().ok(...
write
identifier_name
is_eq.rs
// Compares two token tree lists. Expands to the token tree list inside the first block if the // lists are equivalent, and the second if they are not. Expensive - generates a new macro for // every invocation! This macro is only valid in item position, due to its use of macro_rules. macro_rules! is_eq { ( ...
() { eq_test_1(); eq_test_2(); }
main
identifier_name
is_eq.rs
// Compares two token tree lists. Expands to the token tree list inside the first block if the // lists are equivalent, and the second if they are not. Expensive - generates a new macro for // every invocation! This macro is only valid in item position, due to its use of macro_rules. macro_rules! is_eq { ( ...
{ eq_test_1(); eq_test_2(); }
identifier_body
is_eq.rs
// Compares two token tree lists. Expands to the token tree list inside the first block if the // lists are equivalent, and the second if they are not. Expensive - generates a new macro for // every invocation! This macro is only valid in item position, due to its use of macro_rules. macro_rules! is_eq { ( ...
is_eq_test!($($thingA)*, $($thingB)*); ); } is_eq! { if (a bunch of tokens!) == (another bunch of tokens!) { fn eq_test_1() { println!("They're equal!"); } } else { fn eq_test_1() { println!("As expected, they're not equal."); } } } is_eq! { if (a pile of equivalent tokens...
}
random_line_split
exhaustive_ascii_chars.rs
use malachite_base::chars::exhaustive::exhaustive_ascii_chars; #[test] fn
() { assert_eq!( exhaustive_ascii_chars().collect::<String>(), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&\'()*+,-./:;<=>?@[\\\ ]^_`{|}~\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\ \u{12}\u{13}\u{14}\u{15}\u{16}\u{17}...
test_exhaustive_ascii_chars
identifier_name
exhaustive_ascii_chars.rs
use malachite_base::chars::exhaustive::exhaustive_ascii_chars; #[test] fn test_exhaustive_ascii_chars() { assert_eq!( exhaustive_ascii_chars().collect::<String>(), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&\'()*+,-./:;<=>?@[\\\ ]^_`{|}~\u{0}\u{1}\u{2}\u{3}\u{4}\u...
assert_eq!(exhaustive_ascii_chars().count(), 1 << 7); }
random_line_split
exhaustive_ascii_chars.rs
use malachite_base::chars::exhaustive::exhaustive_ascii_chars; #[test] fn test_exhaustive_ascii_chars()
{ assert_eq!( exhaustive_ascii_chars().collect::<String>(), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !\"#$%&\'()*+,-./:;<=>?@[\\\ ]^_`{|}~\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\ \u{12}\u{13}\u{14}\u{15}\u{16}\u{17}\u...
identifier_body
tests.rs
#[test] fn get_index() { let _ = pretty_env_logger::try_init(); let res = warp::test::request() .reply(&crate::index()); assert_eq!(res.status(), 200); assert_eq!(res.headers()["content-type"], "text/html; charset=utf-8"); } #[test] fn get_badge() { let _ = pretty_env_logger::try_init(); ...
.expect("filter no query"); assert_eq!(style, None); }
random_line_split
tests.rs
#[test] fn get_index() { let _ = pretty_env_logger::try_init(); let res = warp::test::request() .reply(&crate::index()); assert_eq!(res.status(), 200); assert_eq!(res.headers()["content-type"], "text/html; charset=utf-8"); } #[test] fn get_badge() { let _ = pretty_env_logger::try_init(); ...
() { let _ = pretty_env_logger::try_init(); let style = warp::test::request() .path("/warp?style=flat-square") .filter(&crate::style()) .expect("filter flat-square"); assert_eq!(style, Some(crate::Style::FlatSquare)); let style = warp::test::request() .path("/warp?style=fl...
badge_style
identifier_name
tests.rs
#[test] fn get_index() { let _ = pretty_env_logger::try_init(); let res = warp::test::request() .reply(&crate::index()); assert_eq!(res.status(), 200); assert_eq!(res.headers()["content-type"], "text/html; charset=utf-8"); } #[test] fn get_badge()
#[test] fn get_badge_404() { let _ = pretty_env_logger::try_init(); let res = warp::test::request() .path("/this-crate-should-never-exist-amirite") .reply(&crate::badge()); assert_eq!(res.status(), 404); } #[test] fn badge_style() { let _ = pretty_env_logger::try_init(); let styl...
{ let _ = pretty_env_logger::try_init(); let res = warp::test::request() .path("/warp") .reply(&crate::badge()); assert_eq!(res.status(), 302); assert_eq!(res.headers()["expires"], "Sun, 01 Jan 1990 00:00:00 GMT"); assert_eq!(res.headers()["pragma"], "no-cache"); assert_eq!( ...
identifier_body
instr_cmpss.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn cmpss_1() { run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM0...
fn cmpss_2() { run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM7)), operand2: Some(IndirectDisplaced(ECX, 712415121, Some(OperandSize::Dword), None)), operand3: Some(Literal8(19)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None...
} #[test]
random_line_split
instr_cmpss.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn
() { run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM4)), operand3: Some(Literal8(94)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[243, 15, 194, 196, 94], OperandSize::Dword) } #[test] fn...
cmpss_1
identifier_name
instr_cmpss.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn cmpss_1() { run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM0...
{ run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM7)), operand2: Some(IndirectDisplaced(RAX, 1640090676, Some(OperandSize::Dword), None)), operand3: Some(Literal8(26)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[243, 1...
identifier_body
sinf64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::sinf64; use core::num::Float; use core::f64; use core::f64::consts::PI; // pub fn sinf64(x: f64) -> f64; #[test] fn sinf64_test1() { let x: f64 = f64::nan(); let result: f6...
() { let x: f64 = 90.0 * PI / 180.0; let result: f64 = unsafe { sinf64(x) }; assert_eq!(result, 1.0); } }
sinf64_test6
identifier_name
sinf64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::sinf64; use core::num::Float; use core::f64; use core::f64::consts::PI; // pub fn sinf64(x: f64) -> f64; #[test] fn sinf64_test1() { let x: f64 = f64::nan(); let result: f6...
#[test] fn sinf64_test5() { let x: f64 = 45.0 * PI / 180.0; let result: f64 = unsafe { sinf64(x) }; assert_eq!(result, 0.7071067811865475); } #[test] fn sinf64_test6() { let x: f64 = 90.0 * PI / 180.0; let result: f64 = unsafe { sinf64(x) }; assert_eq!(result, 1.0); } }
{ let x: f64 = 0.0 * PI / 180.0; let result: f64 = unsafe { sinf64(x) }; assert_eq!(result, 0.0); }
identifier_body
sinf64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::sinf64; use core::num::Float; use core::f64; use core::f64::consts::PI; // pub fn sinf64(x: f64) -> f64; #[test] fn sinf64_test1() { let x: f64 = f64::nan(); let result: f6...
} }
assert_eq!(result, 1.0);
random_line_split
focusevent.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::FocusEventBinding; use dom::bindings::codegen::Bindings::FocusEventBinding::...
else { EventBubbles::DoesNotBubble }; let cancelable = if init.parent.parent.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; let event = FocusEvent::new(global.as_window(), type_, ...
{ EventBubbles::Bubbles }
conditional_block
focusevent.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::FocusEventBinding; use dom::bindings::codegen::Bindings::FocusEventBinding::...
() -> FocusEvent { FocusEvent { uievent: UIEvent::new_inherited(), related_target: Default::default(), } } pub fn new(window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, vie...
new_inherited
identifier_name
focusevent.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::FocusEventBinding;
use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::reflector::reflect_dom_object; use dom::event::{EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; u...
use dom::bindings::codegen::Bindings::FocusEventBinding::FocusEventMethods; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
random_line_split
focusevent.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::FocusEventBinding; use dom::bindings::codegen::Bindings::FocusEventBinding::...
// https://dom.spec.whatwg.org/#dom-event-istrusted fn IsTrusted(&self) -> bool { self.uievent.IsTrusted() } }
{ self.related_target.get() }
identifier_body
index.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
<E>(self, value: String) -> Result<Self::Value, E> where E: Error, { self.visit_str(value.as_ref()) } } #[cfg(test)] mod tests { use super::*; use serde_json; #[test] fn block_number_deserialization() { let s = r#"["0xa", "10"]"#; let deserialized: Vec<Index...
visit_string
identifier_name
index.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn visit_string<E>(self, value: String) -> Result<Self::Value, E> where E: Error, { self.visit_str(value.as_ref()) } } #[cfg(test)] mod tests { use super::*; use serde_json; #[test] fn block_number_deserialization() { let s = r#"["0xa", "10"]"#; let de...
{ match value { _ if value.starts_with("0x") => usize::from_str_radix(&value[2..], 16).map(Index).map_err(|_| Error::custom("invalid index")), _ => value.parse::<usize>().map(Index).map_err(|_| Error::custom("invalid index")), } }
identifier_body
index.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
where E: Error, { self.visit_str(value.as_ref()) } } #[cfg(test)] mod tests { use super::*; use serde_json; #[test] fn block_number_deserialization() { let s = r#"["0xa", "10"]"#; let deserialized: Vec<Index> = serde_json::from_str(s).unwrap(); asser...
random_line_split
snapshot.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A gecko snapshot, that stores the element attributes and state before they //! change in order to properly cal...
(&self) -> String { use nsstring::nsCString; let mut string = nsCString::new(); unsafe { bindings::Gecko_Snapshot_DebugListAttributes(self, &mut string); } String::from_utf8_lossy(&*string).into_owned() } fn state(&self) -> Option<ElementState> { if s...
debug_list_attributes
identifier_name
snapshot.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A gecko snapshot, that stores the element attributes and state before they //! change in order to properly cal...
CaseSensitivity::CaseSensitive => false, CaseSensitivity::AsciiCaseInsensitive => true, }; // FIXME: case sensitivity for operators other than Equal match operator { AttrSelectorOperator::...
random_line_split
snapshot.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A gecko snapshot, that stores the element attributes and state before they //! change in order to properly cal...
local_name.as_ptr(), expected_value.as_ptr(), ignore_case, ), AttrSelectorOperator::Includes => bindings::Gecko_SnapshotAttrIncludes( self, ...
{ unsafe { match *operation { AttrSelectorOperation::Exists => { bindings::Gecko_SnapshotHasAttr(self, ns.atom_or_null(), local_name.as_ptr()) }, AttrSelectorOperation::WithValue { operator, c...
identifier_body
initrd.rs
//! Initial ramdisk driver use alloc::string::String; use alloc::vec::Vec; use hashbrown::HashMap; use x86_64::{PhysAddr, VirtAddr}; use d7initrd::{FileEntry, HEADER_MAGIC, HEADER_SIZE_BYTES}; use crate::memory::{self, phys_to_virt, prelude::*}; use crate::util::elf_parser::{self, ELFData, ELFHeader, ELFProgramHeade...
/// Files by name. files: HashMap<String, FileEntry>, /// A slice containing all files, concatenated. /// The lifetime is static, as these are never deallocated. slice: &'static [u8], } static INITRD: spin::Once<InitRD> = spin::Once::new(); pub fn init(elf_data: ELFData) { unsafe { // ...
#[derive(Debug)] struct InitRD {
random_line_split
initrd.rs
//! Initial ramdisk driver use alloc::string::String; use alloc::vec::Vec; use hashbrown::HashMap; use x86_64::{PhysAddr, VirtAddr}; use d7initrd::{FileEntry, HEADER_MAGIC, HEADER_SIZE_BYTES}; use crate::memory::{self, phys_to_virt, prelude::*}; use crate::util::elf_parser::{self, ELFData, ELFHeader, ELFProgramHeade...
(elf_data: ELFData) { unsafe { // Get address let start_addr = PhysAddr::from_u64(page_align_up(elf_data.last_addr())); let header = phys_to_virt(start_addr); let hptr: *const u8 = header.as_ptr(); let magic = *(hptr.add(0) as *const u32); let size_flist = *(hptr.add...
init
identifier_name
initrd.rs
//! Initial ramdisk driver use alloc::string::String; use alloc::vec::Vec; use hashbrown::HashMap; use x86_64::{PhysAddr, VirtAddr}; use d7initrd::{FileEntry, HEADER_MAGIC, HEADER_SIZE_BYTES}; use crate::memory::{self, phys_to_virt, prelude::*}; use crate::util::elf_parser::{self, ELFData, ELFHeader, ELFProgramHeade...
{ let rd: &InitRD = INITRD.poll().unwrap(); log::trace!("Read {:?} (found={})", name, rd.files.contains_key(name)); let entry = rd.files.get(name)?; let start = entry.offset as usize; let len = entry.size as usize; Some(&rd.slice[start..start + len]) }
identifier_body
issue-49579.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn fibs(n: u32) -> impl Iterator<Item=u128> { (0.. n) .scan((0, 1), |st, _| { *st = (st.1, st.0 + st.1); Some(*st) }) .map(&|(f, _)| f) } fn main() { println!("{:?}", fibs(10).collect::<Vec<_>>()); }
// ignore-emscripten no i128 support #![feature(nll)]
random_line_split
issue-49579.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { println!("{:?}", fibs(10).collect::<Vec<_>>()); }
{ (0 .. n) .scan((0, 1), |st, _| { *st = (st.1, st.0 + st.1); Some(*st) }) .map(&|(f, _)| f) }
identifier_body
issue-49579.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { println!("{:?}", fibs(10).collect::<Vec<_>>()); }
main
identifier_name
unboxed-closures-extern-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = call_it(&square, 22); let y = call_it_mut(&mut square, 22); let z = call_it_once(square, 22); assert_eq!(x, square(22)); assert_eq!(y, square(22)); assert_eq!(z, square(22)); }
identifier_body
unboxed-closures-extern-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn square(x: int) -> int { x * x } fn call_it<F:Fn(int)->int>(f: &F, x: int) -> int { f(x) } fn call_it_mut<F:FnMut(int)->int>(f: &mut F, x: int) -> int { f(x) } fn call_it_once<F:FnOnce(int)->int>(f: F, x: int) -> int { f(x) } fn main() { let x = call_it(&square, 22); let y = call_it_mut(&mut s...
#![feature(unboxed_closures)] use std::ops::{Fn,FnMut,FnOnce};
random_line_split
unboxed-closures-extern-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(x: int) -> int { x * x } fn call_it<F:Fn(int)->int>(f: &F, x: int) -> int { f(x) } fn call_it_mut<F:FnMut(int)->int>(f: &mut F, x: int) -> int { f(x) } fn call_it_once<F:FnOnce(int)->int>(f: F, x: int) -> int { f(x) } fn main() { let x = call_it(&square, 22); let y = call_it_mut(&mut square, 22...
square
identifier_name
typeinfo.rs
use super::types; // this implements some kind of manual reflection pub trait TypeInfo { fn visit_fields<F>(cb: F) where F: Fn(&str /* name */, usize /* offset */, usize /* count */, types::GlTypeEnum);
macro_rules! impl_typeinfo { ($t:ty, $($field:ident),+) => ( impl $crate::typeinfo::TypeInfo for $t { fn visit_fields<F>(cb: F) where F: Fn(&str, usize, usize, ::types::GlTypeEnum) { use $crate::types::{GlType, ElemCount, GlTypeEnum}; ...
}
random_line_split
cb-cooccur.rs
//! Example 0: Word cooccurrence counter //! //! This simple script takes an input WET corpus piped to STDIN and counts cooccurrences of input //! tokens, where tokens are defined by unicode, and cooccurrence is a window 21 words in //! diameter, and only words from a newline-separated list are considered. //! //! The ...
// It could be usize instead of f64 but this is easier for interop // and its range is still enough not to be a problem. let mut cooccurrences: Array2<f64> = Array2::zeros((words.len() + 1, words.len() + 1)); if words.len() < 25 { info!("Collecting cooccurrences (with one another) of: {:?}", wo...
{ env_logger::init().unwrap(); let args = app_from_crate!() .arg_from_usage("<wordlist> 'file containing words to look for, one per line'") .arg_from_usage("<output> 'file in which to store the resulting cooccurrence matrix'") .get_matches(); // Read the word list from a file. l...
identifier_body
cb-cooccur.rs
//! Example 0: Word cooccurrence counter //! //! This simple script takes an input WET corpus piped to STDIN and counts cooccurrences of input //! tokens, where tokens are defined by unicode, and cooccurrence is a window 21 words in //! diameter, and only words from a newline-separated list are considered. //! //! The ...
(content: &str, ids: &HashMap<&str, usize>) -> Vec<usize> { /// Notice that we return indices (avoiding allocation) content // You can split on nonalphanumerics for a big speedup but the tokens are dubious. //.split(|c: char|! c.is_alphanumeric()) .split_word_bounds() .map(|mention...
tokenize
identifier_name
cb-cooccur.rs
//! Example 0: Word cooccurrence counter //! //! This simple script takes an input WET corpus piped to STDIN and counts cooccurrences of input //! tokens, where tokens are defined by unicode, and cooccurrence is a window 21 words in //! diameter, and only words from a newline-separated list are considered. //! //! The ...
else { info!("Collecting cooccurrences (with one another) of {} words.", words.len()); } for rec in WarcStreamer::new()? { let mention_ids = tokenize(&rec, &word_ids); for mention_i in 0..mention_ids.len() { for context_i in mention_i..min(mention_ids.len(), WINDOW_WIDT...
{ info!("Collecting cooccurrences (with one another) of: {:?}", words); }
conditional_block
cb-cooccur.rs
//! Example 0: Word cooccurrence counter //! //! This simple script takes an input WET corpus piped to STDIN and counts cooccurrences of input //! tokens, where tokens are defined by unicode, and cooccurrence is a window 21 words in //! diameter, and only words from a newline-separated list are considered.
//! The output is a numpy file with a cooccurrence matrix. The rows are the center word, starting //! with the unknown word as word 0, and proceeding in the order they were specified in the input //! word list. The columns are the context words, and cooccurrence is always counted as 1 or 0. //! // argument parsing #[m...
//!
random_line_split
spsc_queue.rs
/* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of con...
} tx.send(()).unwrap(); }); for _ in 0..100000 { q.push(1); } rx.recv().unwrap(); } } }
{ unsafe { stress_bound(0); stress_bound(1); } unsafe fn stress_bound(bound: uint) { let q = Arc::new(Queue::new(bound)); let (tx, rx) = channel(); let q2 = q.clone(); let _t = Thread::spawn(move|| { for _ ...
identifier_body
spsc_queue.rs
/* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of con...
() { unsafe { let q = Queue::new(0); q.push(box 1); q.push(box 2); } } #[test] fn smoke_bound() { unsafe { let q = Queue::new(0); q.push(1); q.push(2); assert_eq!(q.pop(), Some(1)); asser...
drop_full
identifier_name
spsc_queue.rs
/* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of con...
let ret = *self.first.get(); *self.first.get() = (*ret).next.load(Ordering::Relaxed); return ret; } // If the above fails, then update our copy of the tail and try // again. *self.tail_copy.get() = self.tail_prev.load(Ordering::Acquire); if *s...
{ let b = self.cache_subtractions.load(Ordering::Relaxed); self.cache_subtractions.store(b + 1, Ordering::Relaxed); }
conditional_block
spsc_queue.rs
/* Copyright (c) 2010-2011 Dmitry Vyukov. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of con...
queue.push(1); queue.push(2); assert_eq!(queue.pop(), Some(1)); assert_eq!(queue.pop(), Some(2)); assert_eq!(queue.pop(), None); queue.push(3); queue.push(4); assert_eq!(queue.pop(), Some(3)); assert_eq!(queue.po...
fn smoke() { unsafe { let queue = Queue::new(0);
random_line_split
mozmap.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 `MozMap` (open-ended dictionary) type. use crate::dom::bindings::conversions::jsid_to_string; use crate::...
(&self) -> &HashMap<DOMString, T> { &self.map } } impl<T, C> FromJSValConvertible for MozMap<T> where T: FromJSValConvertible<Config = C>, C: Clone, { type Config = C; unsafe fn from_jsval( cx: *mut JSContext, value: HandleValue, config: C, ) -> Result<Conversion...
deref
identifier_name
mozmap.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 `MozMap` (open-ended dictionary) type. use crate::dom::bindings::conversions::jsid_to_string; use crate::...
impl<T> MozMap<T> { /// Create an empty `MozMap`. pub fn new() -> Self { MozMap { map: HashMap::new(), } } } impl<T> Deref for MozMap<T> { type Target = HashMap<DOMString, T>; fn deref(&self) -> &HashMap<DOMString, T> { &self.map } } impl<T, C> FromJSValCo...
/// The `MozMap` (open-ended dictionary) type. #[derive(Clone, JSTraceable)] pub struct MozMap<T> { map: HashMap<DOMString, T>, }
random_line_split
mozmap.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 `MozMap` (open-ended dictionary) type. use crate::dom::bindings::conversions::jsid_to_string; use crate::...
} }
{ rooted!(in(cx) let js_object = JS_NewPlainObject(cx)); assert!(!js_object.handle().is_null()); rooted!(in(cx) let mut js_value = UndefinedValue()); for (key, value) in &self.map { let key = key.encode_utf16().collect::<Vec<_>>(); value.to_jsval(cx, js_value.han...
identifier_body
mozmap.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 `MozMap` (open-ended dictionary) type. use crate::dom::bindings::conversions::jsid_to_string; use crate::...
rooted!(in(cx) let object = value.to_object()); let ids = IdVector::new(cx); if!GetPropertyKeys( cx, object.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, ids.get(), ) { // TODO: can GetPropertyKeys fail? ...
{ return Ok(ConversionResult::Failure( "MozMap value was not an object".into(), )); }
conditional_block
ssh_key.rs
// id number This is a unique identification number for the // key. This can be used to reference a specific SSH key when you wish to embed // a key into a Droplet. // fingerprint string This attribute contains the fingerprint value // that is generated from the public key. This is a unique...
} impl fmt::Display for SshKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ID: {:.0}\n\ Fingerprint: {}\n\ Public Key: {}\n\ Name: {}", self.id, self.fingerprint, self....
{ "ssh_key".into() }
identifier_body
ssh_key.rs
// id number This is a unique identification number for the // key. This can be used to reference a specific SSH key when you wish to embed // a key into a Droplet. // fingerprint string This attribute contains the fingerprint value // that is generated from the public key. This is a unique...
<'a>() -> Cow<'a, str> { "ssh_key".into() } } impl fmt::Display for SshKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ID: {:.0}\n\ Fingerprint: {}\n\ Public Key: {}\n\ Name: {}", self.id, ...
name
identifier_name
ssh_key.rs
// id number This is a unique identification number for the // key. This can be used to reference a specific SSH key when you wish to embed // a key into a Droplet. // fingerprint string This attribute contains the fingerprint value // that is generated from the public key. This is a unique...
use response; #[derive(Deserialize, Debug)] pub struct SshKey { pub id: f64, pub fingerprint: String, pub public_key: String, pub name: String, } impl response::NotArray for SshKey {} impl NamedResponse for SshKey { fn name<'a>() -> Cow<'a, str> { "ssh_key".into() } } impl fmt::Display for SshKe...
random_line_split
x86stdcall.rs
// Copyright 2012-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-MI...
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd", target_os = "android"))] pub fn main() { }
{ unsafe { let expected = 1234_usize; kernel32::SetLastError(expected); let actual = kernel32::GetLastError(); println!("actual = {}", actual); assert_eq!(expected, actual); } }
identifier_body
x86stdcall.rs
// Copyright 2012-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-MI...
() { unsafe { let expected = 1234_usize; kernel32::SetLastError(expected); let actual = kernel32::GetLastError(); println!("actual = {}", actual); assert_eq!(expected, actual); } } #[cfg(any(target_os = "macos", target_os = "linux", target_os = "freeb...
main
identifier_name
x86stdcall.rs
// Copyright 2012-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-MI...
target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "bitrig", target_os = "openbsd", target_os = "android"))] pub fn main() { }
assert_eq!(expected, actual); } } #[cfg(any(target_os = "macos",
random_line_split
TestMad.rs
/* * Copyright (C) 2016 The Android Open Source Project * * 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 app...
float3 __attribute__((kernel)) testMadFloat3Float3Float3Float3(float3 inMultiplicand1, unsigned int x) { float3 inMultiplicand2 = rsGetElementAt_float3(gAllocInMultiplicand2, x); float3 inOffset = rsGetElementAt_float3(gAllocInOffset, x); return mad(inMultiplicand1, inMultiplicand2, inOffset); } float4 __...
}
random_line_split
main.rs
#![allow(unused_variables)] extern crate rustc_serialize; #[macro_use] extern crate serde_derive; extern crate docopt; extern crate sdl2; extern crate num; extern crate rand; #[macro_use] extern crate enum_primitive as ep; mod chip8; mod screen; mod instruction; use docopt::Docopt; use sdl2::keyboard::Keycode; use s...
Keycode::Q => chip8.press(0x4), Keycode::W => chip8.press(0x5), Keycode::E => chip8.press(0x6), Keycode::R => chip8.press(0xd), Keycode::A => chip8.press(0x7), K...
random_line_split
main.rs
#![allow(unused_variables)] extern crate rustc_serialize; #[macro_use] extern crate serde_derive; extern crate docopt; extern crate sdl2; extern crate num; extern crate rand; #[macro_use] extern crate enum_primitive as ep; mod chip8; mod screen; mod instruction; use docopt::Docopt; use sdl2::keyboard::Keycode; use s...
() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); let ctx = sdl2::init().unwrap(); let mut chip8 = Chip8::new(&ctx); let mut events = ctx.event_pump().unwrap(); chip8.load_rom(&args.arg_file); 'main: loop { for event i...
main
identifier_name
trace.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/. */ //! Utilities for tracing JS-managed values. //! //! The lifetime of DOM objects is managed by the SpiderMonkey Ga...
} impl<T: JSTraceable + Copy> JSTraceable for Cell<T> { fn trace(&self, trc: *mut JSTracer) { self.get().trace(trc) } } impl<T: JSTraceable> JSTraceable for UnsafeCell<T> { fn trace(&self, trc: *mut JSTracer) { unsafe { (*self.get()).trace(trc) } } } impl JSTraceable for Heap<*mut J...
{ (**self).trace(trc) }
identifier_body
trace.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/. */ //! Utilities for tracing JS-managed values. //! //! The lifetime of DOM objects is managed by the SpiderMonkey Ga...
: JSTraceable>(traceable: &T) { ROOTED_TRACEABLES.with(|ref traceables| { let mut traceables = traceables.borrow_mut(); let idx = match traceables.set.iter() .rposition(|x| x.ptr == traceable as *const T as *const _) { So...
move<T
identifier_name
trace.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/. */ //! Utilities for tracing JS-managed values. //! //! The lifetime of DOM objects is managed by the SpiderMonkey Ga...
impl<'a, T: JSTraceable> Drop for RootedTraceable<'a, T> { fn drop(&mut self) { unsafe { RootedTraceableSet::remove(self.ptr); } } } /// A vector of items that are rooted for the lifetime of this struct. #[allow(unrooted_must_root)] #[no_move] #[derive(JSTraceable)] #[allow_unrooted...
random_line_split
0009_simple_multiplication_with_stdin.rs
// Compute product of two numbers while accepting value from standard input. use std::io; // imports io library from standard library fn main() { let mut a = String::new(); //creates new, empty String let mut b = String::new(); let c: u32; println!("Enter value a:"); io::stdin().read_line(&mut a...
//Shadowing lets us to re-use the old name. // parse() method on String converts the String into number let a: u32 = a.trim().parse() .ok() .expect("Please type a number"); let b: u32 = b.trim().parse() .ok() .expect("Please type a number"); c =...
.expect("Failed to read value");
random_line_split
0009_simple_multiplication_with_stdin.rs
// Compute product of two numbers while accepting value from standard input. use std::io; // imports io library from standard library fn
() { let mut a = String::new(); //creates new, empty String let mut b = String::new(); let c: u32; println!("Enter value a:"); io::stdin().read_line(&mut a) .ok() .expect("Failed to read value"); println!("Enter value b:"); io::stdin().read_line(&mut b) ...
main
identifier_name
0009_simple_multiplication_with_stdin.rs
// Compute product of two numbers while accepting value from standard input. use std::io; // imports io library from standard library fn main()
let b: u32 = b.trim().parse() .ok() .expect("Please type a number"); c = a * b; println!("Product of {} * {} is {} ", a, b, c); }
{ let mut a = String::new(); //creates new, empty String let mut b = String::new(); let c: u32; println!("Enter value a:"); io::stdin().read_line(&mut a) .ok() .expect("Failed to read value"); println!("Enter value b:"); io::stdin().read_line(&mut b) ...
identifier_body
init-res-into-things.rs
// run-pass #![allow(non_camel_case_types)] #![allow(dead_code)] #![feature(box_syntax)] use std::cell::Cell; // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r<'a> { i: &'a Cell<isize>, } struct BoxR<'a> { x: r<'a> } impl<'a...
<'a> { t0(r<'a>), } let i = &Cell::new(0); { let _a = t::t0(r(i)); } assert_eq!(i.get(), 1); } fn test_tup() { let i = &Cell::new(0); { let _a = (r(i), 0); } assert_eq!(i.get(), 1); } fn test_unique() { let i = &Cell::new(0); { let _a: Box<_...
t
identifier_name
init-res-into-things.rs
// run-pass #![allow(non_camel_case_types)] #![allow(dead_code)] #![feature(box_syntax)] use std::cell::Cell; // Resources can't be copied, but storing into data structures counts // as a move unless the stored thing is used afterwards. struct r<'a> { i: &'a Cell<isize>, } struct BoxR<'a> { x: r<'a> } impl<'a...
} let i = &Cell::new(0); { let _a = t::t0(r(i)); } assert_eq!(i.get(), 1); } fn test_tup() { let i = &Cell::new(0); { let _a = (r(i), 0); } assert_eq!(i.get(), 1); } fn test_unique() { let i = &Cell::new(0); { let _a: Box<_> = box r(i); } as...
fn test_tag() { enum t<'a> { t0(r<'a>),
random_line_split
dump.rs
extern crate wasmparser; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::str; use wasmparser::Parser; use wasmparser::ParserState; use wasmparser::WasmDecoder; fn main() { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { println!("Usage: {} in.wasm", args...
loop { print!("0x{:08x}\t", parser.current_position()); let state = parser.read(); match *state { ParserState::ExportSectionEntry { field, ref kind, index, } => { println!( "ExportSect...
return; } let buf: Vec<u8> = read_wasm(&args[1]).unwrap(); let mut parser = Parser::new(&buf);
random_line_split
dump.rs
extern crate wasmparser; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::str; use wasmparser::Parser; use wasmparser::ParserState; use wasmparser::WasmDecoder; fn
() { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { println!("Usage: {} in.wasm", args[0]); return; } let buf: Vec<u8> = read_wasm(&args[1]).unwrap(); let mut parser = Parser::new(&buf); loop { print!("0x{:08x}\t", parser.current_position()); let...
main
identifier_name
dump.rs
extern crate wasmparser; use std::env; use std::fs::File; use std::io; use std::io::prelude::*; use std::str; use wasmparser::Parser; use wasmparser::ParserState; use wasmparser::WasmDecoder; fn main() { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { println!("Usage: {} in.wasm", args...
{ let mut data = Vec::new(); let mut f = File::open(file)?; f.read_to_end(&mut data)?; Ok(data) }
identifier_body
condvar.rs
use crate::ffi::c_void; use crate::ptr; use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use crate::sys::hermit::abi; use crate::sys::mutex::Mutex; use crate::time::Duration; // The implementation is inspired by Andrew D. Birrell's paper // "Implementing Condition Variables with Semaphores" pub struct Condva...
(&self) { let _ = abi::sem_destroy(self.sem1); let _ = abi::sem_destroy(self.sem2); } }
destroy
identifier_name
condvar.rs
use crate::ffi::c_void; use crate::ptr; use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use crate::sys::hermit::abi; use crate::sys::mutex::Mutex; use crate::time::Duration; // The implementation is inspired by Andrew D. Birrell's paper // "Implementing Condition Variables with Semaphores" pub struct Condva...
} pub unsafe fn notify_all(&self) { let counter = self.counter.swap(0, SeqCst); for _ in 0..counter { abi::sem_post(self.sem1); } for _ in 0..counter { abi::sem_timedwait(self.sem2, 0); } } pub unsafe fn wait(&self, mutex: &Mutex) { ...
{ self.counter.fetch_sub(1, SeqCst); abi::sem_post(self.sem1); abi::sem_timedwait(self.sem2, 0); }
conditional_block
condvar.rs
use crate::ffi::c_void; use crate::ptr; use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use crate::sys::hermit::abi; use crate::sys::mutex::Mutex; use crate::time::Duration; // The implementation is inspired by Andrew D. Birrell's paper // "Implementing Condition Variables with Semaphores" pub struct Condva...
mutex.unlock(); let millis = dur.as_millis().min(u32::MAX as u128) as u32; let res = if millis > 0 { abi::sem_timedwait(self.sem1, millis) } else { abi::sem_trywait(self.sem1) }; abi::sem_post(self.sem2); mutex.lock(); res == 0 ...
self.counter.fetch_add(1, SeqCst);
random_line_split
condvar.rs
use crate::ffi::c_void; use crate::ptr; use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use crate::sys::hermit::abi; use crate::sys::mutex::Mutex; use crate::time::Duration; // The implementation is inspired by Andrew D. Birrell's paper // "Implementing Condition Variables with Semaphores" pub struct Condva...
pub unsafe fn init(&mut self) { let _ = abi::sem_init(&mut self.sem1 as *mut *const c_void, 0); let _ = abi::sem_init(&mut self.sem2 as *mut *const c_void, 0); } pub unsafe fn notify_one(&self) { if self.counter.load(SeqCst) > 0 { self.counter.fetch_sub(1, SeqCst); ...
{ Condvar { counter: AtomicUsize::new(0), sem1: ptr::null(), sem2: ptr::null() } }
identifier_body
ast_clone.rs
use std::str::FromStr; use { proc_macro2::{Span, TokenStream}, syn::{ self, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed, Generics, Ident, Variant, }, }; use crate::{ attr, shared::{map_lifetimes, map_type_params, split_for_impl}, }; pub fn de...
fn create_ast_clone_bounds(generics: &Generics) -> Vec<TokenStream> { map_type_params(generics, |ty| { quote! { #ty: gluon_base::ast::AstClone<'ast, Id> } }) } fn create_lifetime_bounds(generics: &Generics) -> Vec<TokenStream> { map_lifetimes(generics, |_lifetime| { qu...
{ let fields = fields.into_iter().map(|field| { let field_ty = &field.ty; let field_ident = field .ident .as_ref() .expect("Struct fields always have names"); quote! { #field_ident: <#field_ty as gluon_base::ast::AstClone<_>>::ast_clone(#field_...
identifier_body
ast_clone.rs
use std::str::FromStr; use { proc_macro2::{Span, TokenStream}, syn::{ self, Data, DataEnum, DataStruct, DeriveInput, Field, Fields, FieldsNamed, FieldsUnnamed, Generics, Ident, Variant, }, }; use crate::{ attr, shared::{map_lifetimes, map_type_params, split_for_impl}, }; pub fn de...
quote! { #[allow(non_upper_case_globals)] const #dummy_const: () = { use crate as gluon_base; #[automatically_derived] #[allow(unused_attributes, unused_variables)] impl #impl_generics gluon_base::ast::AstClone<'ast, Id> for #ident #ty_generics ...
quote! { #b, } });
random_line_split