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
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn build_map<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uin...
// Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k in goals.iter() { for n in neighbors(k).iter() { // XXX: Extra clone op here, should just shuffle references until // things get clon...
assert!(goals.len() > 0); let mut ret = HashMap::new();
random_line_split
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn build_map<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uin...
for k in edge.iter() { ret.insert(k.clone(), dist); } let mut new_edge = ~HashSet::new(); for k in edge.iter() { for n in neighbors(k).iter() { if!ret.contains_key(n) { new_edge.insert(n.clone()); } } } edge = new_edge...
{ assert!(goals.len() > 0); let mut ret = HashMap::new(); // Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k in goals.iter() { for n in neighbors(k).iter() { // XXX: Extra clone op here, s...
identifier_body
state.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
/// The current margins. pub fn margin(&self) -> &Margin { &self.margin } /// Resize the state. pub fn resize(&mut self, width: u32, height: u32) { let (m, s) = (self.config.style().margin(), self.config.style().spacing()); self.margin.horizontal = m + ((width - (m * 2)) % self.font.width()) / 2; sel...
(self.width - (self.margin.horizontal * 2)) / self.font.width() }
identifier_body
state.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
lse { 0 }) } }
1 } e
conditional_block
state.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
mut self, width: u32, height: u32) { let (m, s) = (self.config.style().margin(), self.config.style().spacing()); self.margin.horizontal = m + ((width - (m * 2)) % self.font.width()) / 2; self.margin.vertical = m + ((height - (m * 2)) % (self.font.height() + s)) / 2; self.width = width; self.height =...
size(&
identifier_name
state.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
.saturating_sub(h.saturating_sub(self.width - (region.x + region.width))) as f32; // Remove margins from height. let h = region.height .saturating_sub(v.saturating_sub(region.y)) .saturating_sub(v.saturating_sub(self.height - (region.y + region.height))) as f32; let x = (x / width).floor() as u32; le...
random_line_split
size_of_in_element_count.rs
//! Lint on use of `size_of` or `size_of_val` of T in an expression //! expecting a count of T use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; us...
(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) -> Option<(Ty<'tcx>, &'tcx Expr<'tcx>)> { const FUNCTIONS: [&[&str]; 8] = [ &paths::PTR_COPY_NONOVERLAPPING, &paths::PTR_COPY, &paths::PTR_WRITE_BYTES, &paths::PTR_SWAP_NONOVERLAPPING, &paths::PTR_SLICE_FROM_RAW_PARTS, &p...
get_pointee_ty_and_count_expr
identifier_name
size_of_in_element_count.rs
//! Lint on use of `size_of` or `size_of_val` of T in an expression //! expecting a count of T use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; us...
count_expr.span, LINT_MSG, None, HELP_MSG ); } }; } }
{ const HELP_MSG: &str = "use a count of elements instead of a count of bytes\ , it already gets multiplied by the size of the type"; const LINT_MSG: &str = "found a count of bytes \ instead of a count of elements of `T`"; if_chain! { // Find calls to funct...
identifier_body
size_of_in_element_count.rs
//! Lint on use of `size_of` or `size_of_val` of T in an expression //! expecting a count of T use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_hir::BinOpKind; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; us...
); } }; } }
None, HELP_MSG
random_line_split
crypto.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...
let cipher = match (cipher, cipherparams) { (Some(CipherSer::Aes128Ctr), Some(CipherSerParams::Aes128Ctr(params))) => Cipher::Aes128Ctr(params), (None, _) => return Err(V::Error::missing_field("cipher")), (Some(_), None) => return Err(V::Error::missing_field("cipherparams")), }; let ciphertext = match c...
}
random_line_split
crypto.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_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error> where V: MapVisitor { let mut cipher = None; let mut cipherparams = None; let mut ciphertext = None; let mut kdf = None; let mut kdfparams = None; let mut mac = None; loop { match visitor.visit_key()? { Some(CryptoField::...
{ write!(formatter, "a valid vault crypto object") }
identifier_body
crypto.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: &str) -> Result<Self::Value, E> where E: Error { match value { "cipher" => Ok(CryptoField::Cipher), "cipherparams" => Ok(CryptoField::CipherParams), "ciphertext" => Ok(CryptoField::CipherText), "kdf" => Ok(CryptoField::Kdf), "kdfparams" => Ok(CryptoField::KdfParams), "mac" => Ok(...
visit_str
identifier_name
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn evaluate_directive(invocation_context: &mut DynasmCont...
} Ok(()) } /// In case a directive is unknown, try to skip up to the next ; and resume parsing. fn skip_until_semicolon(input: parse::ParseStream) { let _ = input.step(|cursor| { let mut rest = *cursor; while let Some((tt, next)) = rest.token_tree() { match tt { ...
{ let expr: syn::Expr = input.parse()?; stmts.push(Stmt::ExprSigned(delimited(expr), size)); }
conditional_block
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn evaluate_directive(invocation_context: &mut DynasmCont...
"byte" => directive_const(invocation_context, stmts, input, Size::BYTE)?, "word" => directive_const(invocation_context, stmts, input, Size::WORD)?, "dword" => directive_const(invocation_context, stmts, input, Size::DWORD)?, "qword" => directive_const(invocation_context, stmts, input, S...
invocation_context.current_arch.set_features(&features); }, // ; .byte (expr ("," expr)*)?
random_line_split
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn evaluate_directive(invocation_context: &mut DynasmCont...
while input.peek(Token![,]) { let _: Token![,] = input.parse()?; let ident: syn::Ident = input.parse()?; features.push(ident); } // ;.feature none cancels all features if features.len() == 1 && features[0] == "none" { ...
{ let directive: syn::Ident = input.parse()?; match directive.to_string().as_str() { // TODO: oword, qword, float, double, long double "arch" => { // ; .arch ident let arch: syn::Ident = input.parse()?; if let Some(a) = arch::from_str(arch.to_string().as_str...
identifier_body
directive.rs
use std::collections::hash_map::Entry; use syn::parse; use syn::Token; use quote::quote; use proc_macro_error::emit_error; use crate::common::{Stmt, Size, delimited}; use crate::arch; use crate::DynasmContext; use crate::parse_helpers::ParseOptExt; pub(crate) fn
(invocation_context: &mut DynasmContext, stmts: &mut Vec<Stmt>, input: parse::ParseStream) -> parse::Result<()> { let directive: syn::Ident = input.parse()?; match directive.to_string().as_str() { // TODO: oword, qword, float, double, long double "arch" => { // ;.arch ident ...
evaluate_directive
identifier_name
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the sam...
() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&args[1])); println!("Done! Read {} files....
main
identifier_name
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the sam...
.to_str() .map(|s| DOCS_TO_CHECK.into_iter().any(|d| *d == s)) .unwrap_or(false) }) { let entry = entry.expect("failed to read file"); if!entry.file_type().is_file() { continue; } let entry = entry.path(); if entry.exte...
let mut errors = 0; for entry in walkdir::WalkDir::new(dir).into_iter().filter_entry(|e| { e.depth() != 1 || e.file_name()
random_line_split
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the sam...
} (files_read, errors) } fn main() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&arg...
{ let mut files_read = 0; let mut errors = 0; for entry in walkdir::WalkDir::new(dir).into_iter().filter_entry(|e| { e.depth() != 1 || e.file_name() .to_str() .map(|s| DOCS_TO_CHECK.into_iter().any(|d| *d == s)) .unwrap_or(false) }) { ...
identifier_body
main.rs
use std::env; use std::path::Path; use std::process::{Command, Output}; fn check_html_file(file: &Path) -> usize { let to_mute = &[ // "disabled" on <link> or "autocomplete" on <select> emit this warning "PROPRIETARY_ATTRIBUTE", // It complains when multiple in the same page link to the sam...
} (files_read, errors) } fn main() -> Result<(), String> { let args = env::args().collect::<Vec<_>>(); if args.len()!= 2 { return Err(format!("Usage: {} <doc folder>", args[0])); } println!("Running HTML checker..."); let (files_read, errors) = find_all_html_files(&Path::new(&arg...
{ errors += check_html_file(&entry); files_read += 1; }
conditional_block
sorting.rs
#![feature(test)] extern crate test; extern crate rand; extern crate algs4; use test::Bencher; use rand::{thread_rng, Rng}; use algs4::sorting::*; use algs4::sorting::quicksort::{quick_sort_3way, quick_sort_orig};
// for small array // static SIZE: usize = 10; macro_rules! defbench( ($name:ident, $func:ident) => ( defbench!($name, $func, f64, SIZE); ); ($name:ident, $func:ident, $typ:ty) => ( defbench!($name, $func, $typ, SIZE); ); ($name:ident, $func:ident, $typ:ty, $size:expr) => ( ...
use algs4::fundamentals::knuth_shuffle; static SIZE: usize = 1000;
random_line_split
sorting.rs
#![feature(test)] extern crate test; extern crate rand; extern crate algs4; use test::Bencher; use rand::{thread_rng, Rng}; use algs4::sorting::*; use algs4::sorting::quicksort::{quick_sort_3way, quick_sort_orig}; use algs4::fundamentals::knuth_shuffle; static SIZE: usize = 1000; // for small array // static SIZE: ...
{ let array = thread_rng().gen_iter().take(SIZE).collect::<Vec<f64>>(); b.iter(|| { let mut array = array.clone(); knuth_shuffle(&mut array); }); }
identifier_body
sorting.rs
#![feature(test)] extern crate test; extern crate rand; extern crate algs4; use test::Bencher; use rand::{thread_rng, Rng}; use algs4::sorting::*; use algs4::sorting::quicksort::{quick_sort_3way, quick_sort_orig}; use algs4::fundamentals::knuth_shuffle; static SIZE: usize = 1000; // for small array // static SIZE: ...
(b: &mut Bencher) { let array = thread_rng().gen_iter().take(SIZE).collect::<Vec<f64>>(); b.iter(|| { let mut array = array.clone(); knuth_shuffle(&mut array); }); }
bench_knuth_shuffle
identifier_name
errors.rs
#[cfg(not(target_os = "macos"))] use std::env; use std::io; use std::num; use std::path; use app_dirs; use reqwest; use serde_json; #[cfg(target_os = "macos")] use walkdir; #[derive(Debug, ErrorChain)] #[error_chain(backtrace = "false")] pub enum
{ Msg(String), #[error_chain(foreign)] AppDirs(app_dirs::AppDirsError), #[cfg(not(target_os = "macos"))] #[error_chain(foreign)] EnvVar(env::VarError), #[error_chain(foreign)] Io(io::Error), #[error_chain(foreign)] Parse(num::ParseIntError), #[error_chain(foreign)] Prefix(path::Str...
ErrorKind
identifier_name
errors.rs
#[cfg(not(target_os = "macos"))] use std::env; use std::io; use std::num; use std::path; use app_dirs; use reqwest; use serde_json; #[cfg(target_os = "macos")] use walkdir; #[derive(Debug, ErrorChain)] #[error_chain(backtrace = "false")] pub enum ErrorKind { Msg(String), #[error_chain(foreign)] AppDirs(app_d...
#[error_chain(foreign)] Io(io::Error), #[error_chain(foreign)] Parse(num::ParseIntError), #[error_chain(foreign)] Prefix(path::StripPrefixError), #[error_chain(foreign)] Reqwest(reqwest::Error), #[error_chain(foreign)] SerdeJSON(serde_json::Error), #[cfg(target_os = "macos")] #[error_ch...
#[cfg(not(target_os = "macos"))] #[error_chain(foreign)] EnvVar(env::VarError),
random_line_split
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnum...
else { // Just serialize the u64 version serialize_u64(&self.0,serializer) } } } #[test] fn test_mft_reference() { use std::mem; let raw_reference: &[u8] = &[0x73,0x00,0x00,0x00,0x00,0x00,0x68,0x91]; let mft_reference = MftReference( LittleEndian::read_u64(&raw...
{ serializer.serialize_newtype_struct("mft_reference",&self.get_enum_ref()) }
conditional_block
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnum...
} impl Display for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl Debug for MftReference { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f,"{}",self.0) } } impl ser::Serialize for MftReference { fn serialize<S>(&s...
{ let mut raw_buffer = vec![]; raw_buffer.write_u64::<LittleEndian>(self.0).unwrap(); LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ) }
identifier_body
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnum...
(pub u64); impl MftReference{ pub fn from_entry_and_seq(&mut self, entry: u64, sequence: u16){ let entry_buffer: [u8; 8] = unsafe { transmute(entry.to_le()) }; let seq_buffer: [u8; 2] = unsafe { transmute(sequence.to_le()) }; let mut ref_buffer = vec![...
MftReference
identifier_name
reference.rs
use serde::{ser}; use std::mem::transmute; use byteorder::{ByteOrder, LittleEndian, WriteBytesExt}; use std::fmt::{Display,Debug}; use std::fmt; use serialize::{ serialize_u64 }; // Option to display references as nested pub static mut NESTED_REFERENCE: bool = false; #[derive(Serialize, Debug)] pub struct MftEnum...
reference: LittleEndian::read_u64(&raw_buffer[0..8]), entry: LittleEndian::read_u64( &[&raw_buffer[0..6], &[0,0]].concat() ), sequence: LittleEndian::read_u16(&raw_buffer[6..8]) } } pub fn get_entry_number(&self)->u64{ let mut raw_b...
MftEnumReference{
random_line_split
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <jordy.dickinson@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use st...
} else { if!dest.uu_is_dir() { show_error!("TARGET must be a directory"); panic!(); } for src in sources.iter() { let source = Path::new(&src); if!source.uu_is_file() { show_error!("\"{}\" is not a file", source.display()); ...
{ show_error!("{}", err); panic!(); }
conditional_block
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <jordy.dickinson@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use st...
} fn copy(matches: getopts::Matches) { let sources: Vec<String> = if matches.free.is_empty() { show_error!("Missing SOURCE argument. Try --help."); panic!() } else { // All but the last argument: matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() ...
\n\ {2}", NAME, VERSION, usage); println!("{}", msg);
random_line_split
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <jordy.dickinson@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use st...
(usage: &String) { let msg = format!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n \ or: {0} -t DIRECTORY SOURCE\n\ \n\ {2}", NAME, VERSION, usage); println!("{}", ...
help
identifier_name
cp.rs
#![crate_name = "cp"] /* * This file is part of the uutils coreutils package. * * (c) Jordy Dickinson <jordy.dickinson@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; use getopts::Options; use st...
fn copy(matches: getopts::Matches) { let sources: Vec<String> = if matches.free.is_empty() { show_error!("Missing SOURCE argument. Try --help."); panic!() } else { // All but the last argument: matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() }...
{ let msg = format!("{0} {1}\n\n\ Usage: {0} SOURCE DEST\n \ or: {0} SOURCE... DIRECTORY\n \ or: {0} -t DIRECTORY SOURCE\n\ \n\ {2}", NAME, VERSION, usage); println!("{}", msg); }
identifier_body
scancode_linux.rs
use super::Key; use super::Key::*; /// Keyboard scancode map for Linux. pub static MAP: [Option<Key>; 97] = [ None, None, None, None, None, None, None, None, None, Some(Escape), Some(Num1), Some(Num2), Some(Num3), Some(Num4), Some(Num5), Some(Num6), S...
Some(Z), Some(X), Some(C), Some(V), Some(B), Some(N), Some(M), Some(Comma), Some(Period), Some(Slash), Some(RightShift), Some(PadMultiply), Some(LeftAlt), Some(Space), Some(CapsLock), Some(F1), Some(F2), Some(F3), Some(F4), Some(F5), So...
Some(Semicolon), Some(Apostrophe), Some(Grave), Some(LeftShift), Some(Backslash),
random_line_split
inherent_impl.rs
// run-pass // compile-flags: -Z chalk trait Foo { } impl Foo for i32 { } struct S<T: Foo> { x: T, } fn only_foo<T: Foo>(_x: &T) { } impl<T> S<T> { // Test that we have the correct environment inside an inherent method. fn dummy_foo(&self) { only_foo(&self.x) } } trait Bar { } impl Bar for...
<U: Bar>(&self) { only_foo(&self.x); only_bar::<U>(); } } fn main() { let s = S { x: 5, }; s.dummy_bar::<u32>(); s.dummy_foo(); }
dummy_bar
identifier_name
inherent_impl.rs
// run-pass // compile-flags: -Z chalk trait Foo { } impl Foo for i32 { } struct S<T: Foo> { x: T, } fn only_foo<T: Foo>(_x: &T) { } impl<T> S<T> { // Test that we have the correct environment inside an inherent method. fn dummy_foo(&self) { only_foo(&self.x) } } trait Bar { } impl Bar for...
}; s.dummy_bar::<u32>(); s.dummy_foo(); }
random_line_split
inherent_impl.rs
// run-pass // compile-flags: -Z chalk trait Foo { } impl Foo for i32 { } struct S<T: Foo> { x: T, } fn only_foo<T: Foo>(_x: &T) { } impl<T> S<T> { // Test that we have the correct environment inside an inherent method. fn dummy_foo(&self) { only_foo(&self.x) } } trait Bar { } impl Bar for...
} fn main() { let s = S { x: 5, }; s.dummy_bar::<u32>(); s.dummy_foo(); }
{ only_foo(&self.x); only_bar::<U>(); }
identifier_body
elo.rs
// This file was taken from the rust-elo project since it's not a published // Cargo crate. Check out https://github.com/CarlColglazier/rust-elo :] // disregard dead code since this is an API #![allow(dead_code)] /// Elo. pub trait Elo { /// Get the rating. fn get_rating(&self) -> f32; /// Set the ratin...
/// Returns the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let elo_ranking = EloRanking::new(32); /// assert_eq!(32, elo_ranking.get_k_factor()); /// ``` pub fn get_k_factor(&self) -> usize { return self.k_factor; } /// Internal me...
{ self.k_factor = k; }
identifier_body
elo.rs
// This file was taken from the rust-elo project since it's not a published // Cargo crate. Check out https://github.com/CarlColglazier/rust-elo :] // disregard dead code since this is an API #![allow(dead_code)] /// Elo. pub trait Elo { /// Get the rating. fn get_rating(&self) -> f32; /// Set the ratin...
return EloRanking { k_factor: k, } } /// Change the K factor. /// /// # Example /// /// ``` /// # use elo::EloRanking; /// # let mut elo_ranking = EloRanking::new(32); /// elo_ranking.set_k_factor(25); /// ``` pub fn set_k_factor(&mut self, k: usi...
/// ``` pub fn new(k: usize) -> EloRanking {
random_line_split
elo.rs
// This file was taken from the rust-elo project since it's not a published // Cargo crate. Check out https://github.com/CarlColglazier/rust-elo :] // disregard dead code since this is an API #![allow(dead_code)] /// Elo. pub trait Elo { /// Get the rating. fn get_rating(&self) -> f32; /// Set the ratin...
<T: Elo>(player_one: &T, player_two: &T) -> f32 { return 1.0f32 / (1.0f32 + 10f32.powf( (player_two.get_rating() - player_one.get_rating()) / 400f32 )); } /// EloRanking. pub struct EloRanking { k_factor: usize, } impl EloRanking { /// Create a new Elo ranking system. /// /// # Example...
expected_rating
identifier_name
borrowck-pat-reassign-binding.rs
// Copyright 2012-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 mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred. x = Some(0); } Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } ...
main
identifier_name
borrowck-pat-reassign-binding.rs
// Copyright 2012-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 mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred. x = Some(0); } Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x...
identifier_body
borrowck-pat-reassign-binding.rs
// Copyright 2012-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...
x = Some(0); } Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x.clone(); // just to prevent liveness warnings }
let mut x: Option<isize> = None; match x { None => { // Note: on this branch, no borrow has occurred.
random_line_split
borrowck-pat-reassign-binding.rs
// Copyright 2012-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...
Some(ref i) => { // But on this branch, `i` is an outstanding borrow x = Some(*i+1); //~ ERROR cannot assign to `x` } } x.clone(); // just to prevent liveness warnings }
{ // Note: on this branch, no borrow has occurred. x = Some(0); }
conditional_block
lexical-scope-in-while.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 ...
// debugger:finish // debugger:print x // check:$13 = 2 // debugger:continue fn main() { let mut x = 0; while x < 2 { zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope...
// check:$12 = 102 // debugger:continue
random_line_split
lexical-scope-in-while.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 ...
() { let mut x = 0; while x < 2 { zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz(); sentinel(); ...
main
identifier_name
lexical-scope-in-while.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 ...
sentinel(); let x = -987; zzz(); sentinel(); } // Check that we get the x before the inner scope again zzz(); sentinel(); } zzz(); sentinel(); } fn zzz() {()} fn sentinel() {()}
{ let mut x = 0; while x < 2 { zzz(); sentinel(); x += 1; zzz(); sentinel(); // Shadow x let x = x + 100; zzz(); sentinel(); // open scope within loop's top level scope { zzz();
identifier_body
mod.rs
use sfml::graphics; use engine::resource_loader::{ResourceLoader, Resource}; use engine::state::StateMachine; use engine::rendering::RenderContext; use engine::settings::Settings; use self::State::*; pub mod colors; pub mod main_menu; pub mod game_state; pub mod slot_select_menu; pub mod level; pub mod ui; pub mod s...
{ MainMenuStateID, GameStateID, SlotSelectStateID, OptionsStateID, } pub static NUM_SLOTS : isize = 6; pub fn init_states(state_machine: &mut StateMachine, loader: &ResourceLoader, ctx: &RenderContext, settings: &Settings) { state_machine.add_state(MainMenuStateID as isize, Box::new(main_men...
State
identifier_name
mod.rs
use sfml::graphics; use engine::resource_loader::{ResourceLoader, Resource}; use engine::state::StateMachine; use engine::rendering::RenderContext; use engine::settings::Settings; use self::State::*; pub mod colors; pub mod main_menu; pub mod game_state; pub mod slot_select_menu; pub mod level; pub mod ui; pub mod s...
state_machine.add_state(MainMenuStateID as isize, Box::new(main_menu::MainMenu::new(loader, ctx))); state_machine.set_default_state(MainMenuStateID as isize); state_machine.add_state(SlotSelectStateID as isize, Box::new(slot_select_menu::SlotSelectMenu::new(loader, ctx))); state_machine.add_state(Game...
random_line_split
mod.rs
use sfml::graphics; use engine::resource_loader::{ResourceLoader, Resource}; use engine::state::StateMachine; use engine::rendering::RenderContext; use engine::settings::Settings; use self::State::*; pub mod colors; pub mod main_menu; pub mod game_state; pub mod slot_select_menu; pub mod level; pub mod ui; pub mod s...
pub enum State { MainMenuStateID, GameStateID, SlotSelectStateID, OptionsStateID, } pub static NUM_SLOTS : isize = 6; pub fn init_states(state_machine: &mut StateMachine, loader: &ResourceLoader, ctx: &RenderContext, settings: &Settings) { state_machine.add_state(MainMenuStateID as isize, B...
{ let obelix_font = graphics::Font::new_from_file("res/font/AlegreyaSansSC-Light.ttf").unwrap(); loader.add_resource("MenuFont".to_string(), Resource::Font(obelix_font)); }
identifier_body
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; ext...
let capture = Capture(&*tim2); for c in &CHANNELS { capture.enable(*c); } loop { for c in &CHANNELS { match capture.capture(*c) { Ok(snapshot) => { iprintln!(&itm.stim[0], "{:?}: {:?} ms", c, snapshot); } E...
let tim2 = TIM2.access(prio, thr);
random_line_split
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; ext...
// IDLE LOOP fn idle(ref prio: P0, ref thr: T0) ->! { const CHANNELS: [Channel; 4] = [Channel::_1, Channel::_2, Channel::_3, Channel::_4]; let itm = ITM.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); for c in &CHANNELS { capture.enable(*c); ...
{ let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); capture.init(RESOLUTION, afio, gpioa, rcc); }
identifier_body
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; ext...
(ref prio: P0, thr: &TMax) { let afio = &AFIO.access(prio, thr); let gpioa = &GPIOA.access(prio, thr); let rcc = &RCC.access(prio, thr); let tim2 = TIM2.access(prio, thr); let capture = Capture(&*tim2); capture.init(RESOLUTION, afio, gpioa, rcc); } // IDLE LOOP fn idle(ref prio: P0, ref thr: ...
init
identifier_name
capture2.rs
//! Input capture using TIM2 #![deny(warnings)] #![feature(const_fn)] #![feature(used)] #![no_std] extern crate blue_pill; #[macro_use] extern crate cortex_m; extern crate embedded_hal as hal; // version = "0.2.3" extern crate cortex_m_rt; // version = "0.1.0" #[macro_use] extern crate cortex_m_rtfm as rtfm; ext...
Err(nb::Error::WouldBlock) => {} Err(nb::Error::Other(e)) => panic!("{:?}", e), } } } } // TASKS tasks!(stm32f103xx, {});
{ iprintln!(&itm.stim[0], "{:?}: {:?} ms", c, snapshot); }
conditional_block
schema.rs
diesel::table! { comments (id) { id -> Int4,
body -> Text, created_at -> Timestamp, updated_at -> Timestamp, } } diesel::table! { posts (id) { id -> Int4, user_id -> Int4, title -> Text, body -> Text, created_at -> Timestamp, updated_at -> Timestamp, published_at -> Nullable<...
user_id -> Int4, post_id -> Int4,
random_line_split
flush.rs
use crate::io::AsyncWrite; use pin_project_lite::pin_project; use std::future::Future; use std::io; use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; pin_project! { /// A future used to fully flush an I/O object. /// /// Created by the [`AsyncWriteExt::flush`][flush] funct...
}
{ let me = self.project(); Pin::new(&mut *me.a).poll_flush(cx) }
identifier_body
flush.rs
use crate::io::AsyncWrite; use pin_project_lite::pin_project; use std::future::Future; use std::io; use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; pin_project! { /// A future used to fully flush an I/O object. /// /// Created by the [`AsyncWriteExt::flush`][flush] funct...
A: AsyncWrite + Unpin +?Sized, { type Output = io::Result<()>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let me = self.project(); Pin::new(&mut *me.a).poll_flush(cx) } }
impl<A> Future for Flush<'_, A> where
random_line_split
flush.rs
use crate::io::AsyncWrite; use pin_project_lite::pin_project; use std::future::Future; use std::io; use std::marker::PhantomPinned; use std::pin::Pin; use std::task::{Context, Poll}; pin_project! { /// A future used to fully flush an I/O object. /// /// Created by the [`AsyncWriteExt::flush`][flush] funct...
<A>(a: &mut A) -> Flush<'_, A> where A: AsyncWrite + Unpin +?Sized, { Flush { a, _pin: PhantomPinned, } } impl<A> Future for Flush<'_, A> where A: AsyncWrite + Unpin +?Sized, { type Output = io::Result<()>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Outpu...
flush
identifier_name
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint;
/// effectively "restores" the state of the input iterator when it's handed back. /// /// This is very similar to PutBackN except this iterator only supports 0-2 elements and does not /// use a `Vec`. #[derive(Clone)] pub struct ExactlyOneError<I> where I: Iterator, { first_two: Option<Either<[I::Item; 2], I::I...
/// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as the input iterator. /// /// During the execution of exactly_one the iterator must be mutated. This wrapper
random_line_split
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint; /// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as ...
, Some(Either::Right(second)) => { write!(f, "ExactlyOneError[Second: {:?}, RemainingIter: {:?}]", second, self.inner) } None => { write!(f, "ExactlyOneError[RemainingIter: {:?}]", self.inner) } } } } #[cfg(feature = "use_std")...
{ write!(f, "ExactlyOneError[First: {:?}, Second: {:?}, RemainingIter: {:?}]", first, second, self.inner) }
conditional_block
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint; /// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as ...
} impl<I> ExactSizeIterator for ExactlyOneError<I> where I: ExactSizeIterator {} impl<I> Display for ExactlyOneError<I> where I: Iterator, { fn fmt(&self, f: &mut Formatter) -> FmtResult { let additional = self.additional_len(); if additional > 0 { write!(f, "got at least 2 elem...
{ size_hint::add_scalar(self.inner.size_hint(), self.additional_len()) }
identifier_body
exactly_one_err.rs
#[cfg(feature = "use_std")] use std::error::Error; use std::fmt::{Debug, Display, Formatter, Result as FmtResult}; use std::iter::ExactSizeIterator; use either::Either; use crate::size_hint; /// Iterator returned for the error case of `IterTools::exactly_one()` /// This iterator yields exactly the same elements as ...
(&self) -> (usize, Option<usize>) { size_hint::add_scalar(self.inner.size_hint(), self.additional_len()) } } impl<I> ExactSizeIterator for ExactlyOneError<I> where I: ExactSizeIterator {} impl<I> Display for ExactlyOneError<I> where I: Iterator, { fn fmt(&self, f: &mut Formatter) -> FmtResult { ...
size_hint
identifier_name
text_run.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 app_units::Au; use font::{Font, FontHandleMethods, FontMetrics, IS_WHITESPACE_SHAPING_FLAG, RunMetrics}; use f...
; impl Comparator<CharIndex, GlyphRun> for CharIndexComparator { fn compare(&self, key: &CharIndex, value: &GlyphRun) -> Ordering { if *key < value.range.begin() { Ordering::Less } else if *key >= value.range.end() { Ordering::Greater } else { Ordering::E...
CharIndexComparator
identifier_name
text_run.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 app_units::Au; use font::{Font, FontHandleMethods, FontMetrics, IS_WHITESPACE_SHAPING_FLAG, RunMetrics}; use f...
/// right to left, depending on the bidirectional embedding level). pub fn natural_word_slices_in_visual_order(&'a self, range: &Range<CharIndex>) -> NaturalWordSliceIterator<'a> { // Iterate in reverse order if bidi level is RTL. let reverse = self.bidi_l...
} /// Returns an iterator that over natural word slices in visual order (left to right or
random_line_split
match-vec-unreachable.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: Vec<(isize, isize)> = Vec::new(); let x: &[(isize, isize)] = &x; match *x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern _ => () } let x: Vec<String> = vec!["foo".to_string(), "bar".to_string(), ...
main
identifier_name
match-vec-unreachable.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
// except according to those terms. #![feature(slice_patterns)] #![deny(unreachable_patterns)] fn main() { let x: Vec<(isize, isize)> = Vec::new(); let x: &[(isize, isize)] = &x; match *x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern _ => () }...
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
match-vec-unreachable.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: &[char] = &x; match *x { ['a', 'b', 'c', ref _tail..] => {} ['a', 'b', 'c'] => {} //~ ERROR unreachable pattern _ => {} } }
{ let x: Vec<(isize, isize)> = Vec::new(); let x: &[(isize, isize)] = &x; match *x { [a, (2, 3), _] => (), [(1, 2), (2, 3), b] => (), //~ ERROR unreachable pattern _ => () } let x: Vec<String> = vec!["foo".to_string(), "bar".to_string(), ...
identifier_body
hashset.rs
use std::collections::HashSet; fn main() { let mut a: HashSet<i32> = vec!(1i32, 2, 3).into_iter().collect(); let mut b: HashSet<i32> = vec!(2i32, 3, 4).into_iter().collect(); assert!(a.insert(4)); assert!(a.contains(&4)); // `HashSet::insert()` returns false if // there was a value already pr...
// If a collection's element type implements `Show`, // then the collection implements `Show`. // It usually prints its elements in the format `[elem1, elem2,...]` println!("A: {:?}", a); println!("B: {:?}", b); // Print [1, 2, 3, 4, 5] in arbitrary order println!("Union: {:?}", a.union(&b...
assert!(b.insert(4), "Value 4 is already in set B!"); // FIXME ^ Comment out this line b.insert(5);
random_line_split
hashset.rs
use std::collections::HashSet; fn main()
// Print [1, 2, 3, 4, 5] in arbitrary order println!("Union: {:?}", a.union(&b).collect::<Vec<&i32>>()); // This should print [1] println!("Difference: {:?}", a.difference(&b).collect::<Vec<&i32>>()); // Print [2, 3, 4] in arbitrary order. println!("Intersection: {:?}", a.intersection(&b).coll...
{ let mut a: HashSet<i32> = vec!(1i32, 2, 3).into_iter().collect(); let mut b: HashSet<i32> = vec!(2i32, 3, 4).into_iter().collect(); assert!(a.insert(4)); assert!(a.contains(&4)); // `HashSet::insert()` returns false if // there was a value already present. assert!(b.insert(4), "Value 4 i...
identifier_body
hashset.rs
use std::collections::HashSet; fn
() { let mut a: HashSet<i32> = vec!(1i32, 2, 3).into_iter().collect(); let mut b: HashSet<i32> = vec!(2i32, 3, 4).into_iter().collect(); assert!(a.insert(4)); assert!(a.contains(&4)); // `HashSet::insert()` returns false if // there was a value already present. assert!(b.insert(4), "Value ...
main
identifier_name
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, }
impl DynamicOptional { pub fn none(elem: RuntimeTypeBox) -> DynamicOptional { DynamicOptional { elem, value: None } } pub fn mut_or_default(&mut self) -> ReflectValueMut { if let None = self.value { self.value = Some(self.elem.default_value_ref().to_box()); } sel...
random_line_split
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, } impl DynamicOptional { pu...
(&self) -> Option<ReflectValueRef> { self.value.as_ref().map(ReflectValueBox::as_value_ref) } pub fn set(&mut self, value: ReflectValueBox) { assert_eq!(value.get_type(), self.elem); self.value = Some(value); } }
get
identifier_name
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, } impl DynamicOptional { pu...
pub fn mut_or_default(&mut self) -> ReflectValueMut { if let None = self.value { self.value = Some(self.elem.default_value_ref().to_box()); } self.value.as_mut().unwrap().as_value_mut() } pub fn clear(&mut self) { self.value = None; } pub fn get(&self)...
{ DynamicOptional { elem, value: None } }
identifier_body
optional.rs
use crate::reflect::value::value_ref::ReflectValueMut; use crate::reflect::ReflectValueBox; use crate::reflect::ReflectValueRef; use crate::reflect::RuntimeTypeBox; #[derive(Debug, Clone)] pub(crate) struct DynamicOptional { elem: RuntimeTypeBox, value: Option<ReflectValueBox>, } impl DynamicOptional { pu...
self.value.as_mut().unwrap().as_value_mut() } pub fn clear(&mut self) { self.value = None; } pub fn get(&self) -> Option<ReflectValueRef> { self.value.as_ref().map(ReflectValueBox::as_value_ref) } pub fn set(&mut self, value: ReflectValueBox) { assert_eq!(valu...
{ self.value = Some(self.elem.default_value_ref().to_box()); }
conditional_block
color.rs
Value}; use crate::values::generics::color::{Color as GenericColor, ColorOrAuto as GenericColorOrAuto}; use crate::values::specified::calc::CalcNode; use cssparser::{AngleOrNumber, Color as CSSParserColor, Parser, Token, RGBA}; use cssparser::{BasicParseErrorKind, NumberOrPercentage, ParseErrorKind}; use itoa; use std:...
} impl ToComputedValue for MozFontSmoothingBackgroundColor { type ComputedValue = RGBA; fn to_computed_value(&self, context: &Context) -> RGBA { self.0 .to_computed_value(context) .to_rgba(RGBA::transparent()) } fn from_computed_value(computed: &RGBA) -> Self { ...
{ Color::parse(context, input).map(MozFontSmoothingBackgroundColor) }
identifier_body
color.rs
Value}; use crate::values::generics::color::{Color as GenericColor, ColorOrAuto as GenericColorOrAuto}; use crate::values::specified::calc::CalcNode; use cssparser::{AngleOrNumber, Color as CSSParserColor, Parser, Token, RGBA}; use cssparser::{BasicParseErrorKind, NumberOrPercentage, ParseErrorKind}; use itoa; use std:...
() -> Color { Color::CurrentColor } /// Returns transparent value. #[inline] pub fn transparent() -> Color { // We should probably set authored to "transparent", but maybe it doesn't matter. Color::rgba(RGBA::transparent()) } /// Returns a numeric RGBA color value. ...
currentcolor
identifier_name
color.rs
ComputedValue}; use crate::values::generics::color::{Color as GenericColor, ColorOrAuto as GenericColorOrAuto}; use crate::values::specified::calc::CalcNode; use cssparser::{AngleOrNumber, Color as CSSParserColor, Parser, Token, RGBA}; use cssparser::{BasicParseErrorKind, NumberOrPercentage, ParseErrorKind}; use itoa; ...
TextSelectBackgroundAttention, #[css(skip)] TextHighlightBackground, #[css(skip)] TextHighlightForeground, #[css(skip)] IMERawInputBackground, #[css(skip)] IMERawInputForeground, #[css(skip)] IMERawInputUnderline, #[css(skip)] IMESelectedRawTextBackground, #[css(s...
#[css(skip)] TextSelectForegroundCustom, #[css(skip)] TextSelectBackgroundDisabled, #[css(skip)]
random_line_split
num.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(x: T, base: u8) -> RadixFmt<T, Radix> { RadixFmt(x, Radix::new(base)) } macro_rules! radix_fmt { ($T:ty as $U:ty, $fmt:ident) => { impl fmt::Show for RadixFmt<$T, Radix> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RadixFmt(ref x, radix) => radi...
radix
identifier_name
num.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
f.pad_integral(is_positive, self.prefix(), buf.slice_from(curr)) } } /// A binary (base 2) radix #[deriving(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[deriving(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[deriving(Clone, PartialEq)] struct Decimal; /// A hexadec...
{ // Do the same as above, but accounting for two's complement. for byte in buf.iter_mut().rev() { let n = -(x % base); // Get the current place value. x = x / base; // Deaccumulate the number. *byte...
conditional_block
num.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } /// A binary (base 2) radix #[deriving(Clone, PartialEq)] struct Binary; /// An octal (base 8) radix #[deriving(Clone, PartialEq)] struct Octal; /// A decimal (base 10) radix #[deriving(Clone, PartialEq)] struct Decimal; /// A hexadecimal (base 16) radix, formatted with lower-case characters #[deriving(Clon...
random_line_split
stats.rs
use std::default::Default; use std::ops::{Add}; /// Stats specifies static bonuses for an entity. Stats values can be added /// together to build composites. The Default value for Stats must be an /// algebraic zero element, adding it to any Stats value must leave that value
/// Attack bonus pub attack: i32, /// Damage reduction pub protection: i32, /// Mana pool / mana drain pub mana: i32, /// Ranged attack range. Zero means no ranged capability. pub ranged_range: u32, /// Ranged attack power pub ranged_power: i32, /// Bit flags for intrinsics ...
/// unchanged. #[derive(Copy, Clone, Debug, Default, RustcEncodable, RustcDecodable)] pub struct Stats { /// Generic power level pub power: i32,
random_line_split
stats.rs
use std::default::Default; use std::ops::{Add}; /// Stats specifies static bonuses for an entity. Stats values can be added /// together to build composites. The Default value for Stats must be an /// algebraic zero element, adding it to any Stats value must leave that value /// unchanged. #[derive(Copy, Clone, Debug,...
{ /// Generic power level pub power: i32, /// Attack bonus pub attack: i32, /// Damage reduction pub protection: i32, /// Mana pool / mana drain pub mana: i32, /// Ranged attack range. Zero means no ranged capability. pub ranged_range: u32, /// Ranged attack power pub ra...
Stats
identifier_name
stats.rs
use std::default::Default; use std::ops::{Add}; /// Stats specifies static bonuses for an entity. Stats values can be added /// together to build composites. The Default value for Stats must be an /// algebraic zero element, adding it to any Stats value must leave that value /// unchanged. #[derive(Copy, Clone, Debug,...
pub fn ranged_range(self, ranged_range: u32) -> Stats { Stats { ranged_range: ranged_range,.. self } } pub fn ranged_power(self, ranged_power: i32) -> Stats { Stats { ranged_power: ranged_power,.. self } } } impl Add<Stats> for Stats { type Output = Stats; fn add(self, other: Stats) -> Stats { ...
{ Stats { attack: attack, .. self } }
identifier_body
test.rs
extern crate immeta; use immeta::Dimensions; use immeta::formats::{png, gif, jpeg}; use immeta::markers::{Png, Gif, Jpeg, Webp}; const OWLET_DIM: Dimensions = Dimensions { width: 1280, height: 857 }; const DROP_DIM: Dimensions = Dimensions { width: 238, height: 212 }; const CHERRY_DIM: Dimensions = ...
assert_eq!( blocks.next().unwrap(), &gif::Block::ApplicationExtension(gif::ApplicationExtension { application_identifier: *b"NETSCAPE", authentication_code: *b"2.0" }) ); assert_eq!( blocks.next().unwrap(), &gif::Block::CommentExtension(gif::...
{ let md = immeta::load_from_file("tests/images/drop.gif").unwrap(); assert_eq!(md.mime_type(), "image/gif"); assert_eq!(md.dimensions(), DROP_DIM); let md = md.into::<Gif>().ok().expect("not GIF metadata"); assert_eq!(md.version, gif::Version::V89a); assert_eq!(md.dimensions, DROP_DIM); a...
identifier_body
test.rs
extern crate immeta; use immeta::Dimensions; use immeta::formats::{png, gif, jpeg}; use immeta::markers::{Png, Gif, Jpeg, Webp}; const OWLET_DIM: Dimensions = Dimensions { width: 1280, height: 857 }; const DROP_DIM: Dimensions = Dimensions { width: 238, height: 212 }; const CHERRY_DIM: Dimensions = ...
assert_eq!(md.mime_type(), "image/gif"); assert_eq!(md.dimensions(), OWLET_DIM); let md = md.into::<Gif>().ok().expect("not GIF metadata"); assert_eq!(md.version, gif::Version::V89a); assert_eq!(md.dimensions, OWLET_DIM); assert_eq!(md.global_color_table, Some(gif::ColorTable { size: 2...
random_line_split
test.rs
extern crate immeta; use immeta::Dimensions; use immeta::formats::{png, gif, jpeg}; use immeta::markers::{Png, Gif, Jpeg, Webp}; const OWLET_DIM: Dimensions = Dimensions { width: 1280, height: 857 }; const DROP_DIM: Dimensions = Dimensions { width: 238, height: 212 }; const CHERRY_DIM: Dimensions = ...
() { let md = immeta::load_from_file("tests/images/owlet.gif").unwrap(); assert_eq!(md.mime_type(), "image/gif"); assert_eq!(md.dimensions(), OWLET_DIM); let md = md.into::<Gif>().ok().expect("not GIF metadata"); assert_eq!(md.version, gif::Version::V89a); assert_eq!(md.dimensions, OWLET_DIM);...
test_gif_plain
identifier_name
bloomfilter.rs
use std::hash::{Hash, Hasher, SipHasher}; use std::vec::Vec; pub struct Bloom{ pub vec: Vec<bool> , pub hashes: u32 } impl Bloom { pub fn new(prob: f64, capacity: i32) -> Bloom{ let size = (-(capacity as f64 * prob.ln())/(2_f64.ln().powi(2))).ceil() as u64; let hashes = ((size as f64*2_f64.ln())/capacity ...
(&self, value: String) -> bool { let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; if!self.vec[hash_val as usize]{ return false; } } true } } pub fn ...
contains
identifier_name
bloomfilter.rs
use std::hash::{Hash, Hasher, SipHasher}; use std::vec::Vec; pub struct Bloom{ pub vec: Vec<bool> , pub hashes: u32 } impl Bloom { pub fn new(prob: f64, capacity: i32) -> Bloom
pub fn insert(&mut self, value: String){ let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; self.vec[hash_val as usize] = true } } pub fn contains(&self, value: String) -> bool...
{ let size = (-(capacity as f64 * prob.ln())/(2_f64.ln().powi(2))).ceil() as u64; let hashes = ((size as f64*2_f64.ln())/capacity as f64).ceil() as u32; let mut vec = Vec::new(); for _ in 0..size{ vec.push(false); } Bloom{vec: vec, hashes: hashes} }
identifier_body
bloomfilter.rs
use std::hash::{Hash, Hasher, SipHasher}; use std::vec::Vec; pub struct Bloom{ pub vec: Vec<bool> , pub hashes: u32 } impl Bloom { pub fn new(prob: f64, capacity: i32) -> Bloom{ let size = (-(capacity as f64 * prob.ln())/(2_f64.ln().powi(2))).ceil() as u64; let hashes = ((size as f64*2_f64.ln())/capacity ...
Bloom{vec: vec, hashes: hashes} } pub fn insert(&mut self, value: String){ let mut hash_val = hash(value) % self.vec.len() as u64; for _ in 0..self.hashes{ hash_val = hash(hash_val) % self.vec.len() as u64; self.vec[hash_val as usize] = true } } pub...
random_line_split
bloomfilter.rs
use std::hash::{Hash, Hasher, SipHasher}; use std::vec::Vec; pub struct Bloom{ pub vec: Vec<bool> , pub hashes: u32 } impl Bloom { pub fn new(prob: f64, capacity: i32) -> Bloom{ let size = (-(capacity as f64 * prob.ln())/(2_f64.ln().powi(2))).ceil() as u64; let hashes = ((size as f64*2_f64.ln())/capacity ...
} true } } pub fn hash<T>(obj: T) -> u64 where T: Hash { let mut hasher = SipHasher::new(); obj.hash(&mut hasher); hasher.finish() } pub fn main(){ println!("Hello, world!"); }
{ return false; }
conditional_block
paste.rs
#![crate_name = "paste"] #![feature(collections, core, old_io, old_path, rustc_private)] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <arcterus@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ ...
} else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else { let serial = matches.opt_present("serial"); let delimiters = match matches.opt_str("delimiters") { Some(m) => m, None => "\t".to_string() }; paste(matches.free, s...
{ let program = args[0].clone(); let opts = [ getopts::optflag("s", "serial", "paste one file at a time instead of in parallel"), getopts::optopt("d", "delimiters", "reuse characters from LIST instead of TABs", "LIST"), getopts::optflag("h", "help", "display this help and exit"), ...
identifier_body
paste.rs
#![crate_name = "paste"] #![feature(collections, core, old_io, old_path, rustc_private)] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <arcterus@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ ...
(filenames: Vec<String>, serial: bool, delimiters: &str) { let mut files: Vec<io::BufferedReader<Box<Reader>>> = filenames.into_iter().map(|name| io::BufferedReader::new( if name.as_slice() == "-" { Box::new(io::stdio::stdin_raw()) as Box<Reader> } else { ...
paste
identifier_name
paste.rs
#![crate_name = "paste"] #![feature(collections, core, old_io, old_path, rustc_private)] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <arcterus@mail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ ...
let mut output = "".to_string(); let mut eof_count = 0; for (i, file) in files.iter_mut().enumerate() { if eof[i] { eof_count += 1; } else { match file.read_line() { Ok(line) => output.pus...
random_line_split
keys.rs
//! Types for the primary key space operations. use error::Error; /// Returned by key space API calls. pub type KeySpaceResult = Result<KeySpaceInfo, Error>; /// Information about the result of a successful key space operation. #[derive(Clone, Debug, RustcDecodable)] #[allow(non_snake_case)] pub struct KeySpaceInfo ...
{ /// The new value of the etcd creation index. pub createdIndex: Option<u64>, /// Whether or not the node is a directory. pub dir: Option<bool>, /// An ISO 8601 timestamp for when the key will expire. pub expiration: Option<String>, /// The name of the key. pub key: Option<String>, ...
Node
identifier_name
keys.rs
//! Types for the primary key space operations. use error::Error; /// Returned by key space API calls. pub type KeySpaceResult = Result<KeySpaceInfo, Error>; /// Information about the result of a successful key space operation. #[derive(Clone, Debug, RustcDecodable)] #[allow(non_snake_case)] pub struct KeySpaceInfo ...
/// The previous state of the target node. pub prevNode: Option<Node>, } /// An etcd key-value pair or directory. #[derive(Clone, Debug, RustcDecodable)] #[allow(non_snake_case)] pub struct Node { /// The new value of the etcd creation index. pub createdIndex: Option<u64>, /// Whether or not the no...
pub action: String, /// The etcd `Node` that was operated upon. pub node: Node,
random_line_split
main.rs
use axum::{ routing::{get, post}, Router, }; use cloudevents::Event; use http::StatusCode; use std::net::SocketAddr; use tower_http::trace::TraceLayer; fn echo_app() -> Router { Router::new() .route("/", get(|| async { "hello from cloudevents server" })) .route( "/", p...
() { if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") } tracing_subscriber::fmt::init(); let app = echo_app(); let time = Utc::now(); let j = json!({"hello": "world"}); let request = Request:...
axum_mod_test
identifier_name
main.rs
use axum::{ routing::{get, post}, Router, }; use cloudevents::Event; use http::StatusCode; use std::net::SocketAddr; use tower_http::trace::TraceLayer; fn echo_app() -> Router { Router::new() .route("/", get(|| async { "hello from cloudevents server" })) .route( "/", p...
tracing_subscriber::fmt::init(); let app = echo_app(); let time = Utc::now(); let j = json!({"hello": "world"}); let request = Request::builder() .method(http::Method::POST) .header("ce-specversion", "1.0") .header("ce-id", "0001") .h...
{ std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") }
conditional_block
main.rs
use axum::{ routing::{get, post}, Router, }; use cloudevents::Event; use http::StatusCode; use std::net::SocketAddr; use tower_http::trace::TraceLayer; fn echo_app() -> Router { Router::new() .route("/", get(|| async { "hello from cloudevents server" })) .route( "/", p...
assert_eq!(j.to_string().as_bytes(), body); } }
random_line_split
main.rs
use axum::{ routing::{get, post}, Router, }; use cloudevents::Event; use http::StatusCode; use std::net::SocketAddr; use tower_http::trace::TraceLayer; fn echo_app() -> Router { Router::new() .route("/", get(|| async { "hello from cloudevents server" })) .route( "/", p...
#[cfg(test)] mod tests { use super::echo_app; use axum::{ body::Body, http::{self, Request}, }; use chrono::Utc; use hyper; use serde_json::json; use tower::ServiceExt; // for `app.oneshot()` #[tokio::test] async fn axum_mod_test() { if std::env::var("RUS...
{ if std::env::var("RUST_LOG").is_err() { std::env::set_var("RUST_LOG", "axum_example=debug,tower_http=debug") } tracing_subscriber::fmt::init(); let service = echo_app(); let addr = SocketAddr::from(([127, 0, 0, 1], 8080)); tracing::debug!("listening on {}", addr); axum::Server::bin...
identifier_body
monad.rs
// Copyright 2012-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...
() { assert_eq!(transform(Some(10)), Some("11".to_string())); assert_eq!(transform(None), None); assert!((vec!("hi".to_string())) .bind(|x| vec!(x.clone(), format!("{}!", x)) ) .bind(|x| vec!(x.clone(), format!("{}?", x)) ) == vec!("hi".to_string(), "hi?".to_string(), ...
main
identifier_name