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
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (ca...
, _ => {}, } } } } } impl<'a, S: 'a + EventStopable> Dispatchable<S> for EventDispatcher<'a, EventListener> { fn dispatch(&self, event_name: &str, event: &mut S) { if let Some(listeners) = self.listeners.get(event_name) { for listener ...
{ listeners.remove(index); }
conditional_block
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (ca...
if let Some(mut listeners) = self.listeners.get_mut(event_name) { listeners.push(listener); } } pub fn remove_listener(&mut self, event_name: &'a str, listener: &'a mut L) { if self.listeners.contains_key(event_name) { if let Some(mut listeners) = self.listeners....
if !self.listeners.contains_key(event_name) { self.listeners.insert(event_name, Vec::new()); }
random_line_split
mod.rs
pub mod event; use self::event::EventStopable; use std::collections::HashMap; pub trait ListenerCallable: PartialEq { fn call(&self, event_name: &str, event: &mut EventStopable); } pub struct EventListener { callback: fn(event_name: &str, event: &mut EventStopable), } impl EventListener { pub fn new (ca...
(event_name: &str, event: &mut EventStopable) { println!("callback from event: {}", event_name); event.stop_propagation(); } #[test] fn test_dispatcher() { let event_name = "test_a"; let mut event = Event::new(); let callback_one: fn(event_name: &str, event: &mut Ev...
print_event_info
identifier_name
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show ...
fn main() { if cmd_args().len() < 2 { return usage(); } match cmd_args().skip(1).next().unwrap().as_ref() { "set" => display_set(), "show" => display_show(), arg @ _ => { println!("Incorrect command {}", &arg); usage(); } } }
{ let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { println!("Display {}:\nWidth={}\nHeight={}", device_name(&dev_mode.dmDeviceName), &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } else { println!("Failed to retrieve ...
identifier_body
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show ...
fn display_show() { let mut dev_mode: winapi::DEVMODEW = unsafe { std::mem::zeroed() }; if enum_display_settings(&mut dev_mode) { println!("Display {}:\nWidth={}\nHeight={}", device_name(&dev_mode.dmDeviceName), &dev_mode.dmPelsWidth, &dev_mode.dmPelsHeight); } else { println!("F...
///Shows current display resolution.
random_line_split
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show ...
(display_name: &[u16; winapi::winuser::CCHDEVICENAME]) -> String { let len: usize = display_name.iter().position(|&elem| elem == 0).unwrap_or(0); String::from_utf16_lossy(&display_name[..len]) } #[inline] fn enum_display_settings(dev_mode: &mut winapi::DEVMODEW) -> bool { let dev_mode_p: *mut winapi...
device_name
identifier_name
main.rs
extern crate winapi; extern crate user32; use user32::{EnumDisplaySettingsW, ChangeDisplaySettingsW}; use std::env::args as cmd_args; #[inline(always)] fn usage() { println!("Usage: resolution_tool [command] Commands: set [width] [height] Change display settings. show ...
} }
{ println!("Incorrect command {}", &arg); usage(); }
conditional_block
days.rs
extern crate aoc_2018; #[macro_use] extern crate bencher; use std::fs::File; use std::io::Read; use bencher::Bencher; use aoc_2018::get_impl; fn get_input(day: u32) -> Vec<u8> { let filename = format!("inputs/{:02}.txt", day); let mut buf = Vec::new(); let mut file = File::open(&filename).unwrap(); ...
fn test_part2(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part2(&mut input.as_slice()) }) } macro_rules! day_bench { ( $name:ident, $day:expr ) => { pub mod $name { use super::*; ...
let mut instance = get_impl(day); instance.part1(&mut input.as_slice()) }) }
random_line_split
days.rs
extern crate aoc_2018; #[macro_use] extern crate bencher; use std::fs::File; use std::io::Read; use bencher::Bencher; use aoc_2018::get_impl; fn get_input(day: u32) -> Vec<u8> { let filename = format!("inputs/{:02}.txt", day); let mut buf = Vec::new(); let mut file = File::open(&filename).unwrap(); ...
fn test_part2(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part2(&mut input.as_slice()) }) } macro_rules! day_bench { ( $name:ident, $day:expr ) => { pub mod $name { use super::*; ...
{ let input = get_input(day); bench.iter(|| { let mut instance = get_impl(day); instance.part1(&mut input.as_slice()) }) }
identifier_body
days.rs
extern crate aoc_2018; #[macro_use] extern crate bencher; use std::fs::File; use std::io::Read; use bencher::Bencher; use aoc_2018::get_impl; fn
(day: u32) -> Vec<u8> { let filename = format!("inputs/{:02}.txt", day); let mut buf = Vec::new(); let mut file = File::open(&filename).unwrap(); file.read_to_end(&mut buf).unwrap(); buf } fn test_part1(day: u32, bench: &mut Bencher) { let input = get_input(day); bench.iter(|| { ...
get_input
identifier_name
syntax_test_dyn.rs
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax" // dyn trait fn f(x: dyn T, y: Box<dyn T +'static>, z: &dyn T, // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.parameters meta.generic storage.type.trait // ^^^ m...
let y: Box<dyn Display +'static> = Box::new(BYTE); // ^^^ meta.generic storage.type.trait let _: &dyn (Display) = &BYTE; // ^^^ storage.type.trait let _: &dyn (::std::fmt::Display) = &BYTE; // ^^^ storage.type.trait const DT: &'static dyn C = &V; // ^^^ ...
// ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.return-type storage.type.trait let x: &(dyn 'static + Display) = &BYTE; // ^^^ meta.group storage.type.trait
random_line_split
syntax_test_dyn.rs
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax" // dyn trait fn
(x: dyn T, y: Box<dyn T +'static>, z: &dyn T, // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.parameters meta.generic storage.type.trait // ^^^ meta.function.parameters storage.type.trait f: &dyn Fn(CrateNum) -> bool) -> dyn T...
f
identifier_name
syntax_test_dyn.rs
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax" // dyn trait fn f(x: dyn T, y: Box<dyn T +'static>, z: &dyn T, // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.parameters meta.generic storage.type.trait // ^^^ m...
// dyn is not a keyword in all situations (a "weak" keyword). type A0 = dyn; // ^^^ -storage.type.trait type A1 = dyn::dyn; // ^^^^^ meta.path -storage.type.trait // ^^^ -storage.type.trait type A2 = dyn<dyn, dyn>; // ^^^ meta.generic -storage.type.trait // ^^^ meta.generic...
{ // ^^^ meta.function.parameters storage.type.trait // ^^^ meta.function.return-type storage.type.trait let x: &(dyn 'static + Display) = &BYTE; // ^^^ meta.group storage.type.trait let y: Box<dyn Display + 'static> = Box::new(BYTE); // ^^^ meta.ge...
identifier_body
transform.rs
//! Utilities for graph transformations. use std::cell::{Ref, RefCell, RefMut}; use std::default::Default; use super::interface::{ConcreteGraphMut, Id}; use util::splitvec::SplitVec; // ---------------------------------------------------------------- /// Target-node specifier for use with `Builder::append_edge`. #[d...
=> f(), &Target::AllOutputs => panic!("cannot handle `Target::AllOutputs` variant from `node_id`"), &Target::InputOutput => panic!("cannot handle `Target::InputOutput` variant from `node_id`") } } /// Fetch the ID contained in an `...
&Target::NewOutput | &Target::AutoIntermediate
random_line_split
transform.rs
//! Utilities for graph transformations. use std::cell::{Ref, RefCell, RefMut}; use std::default::Default; use super::interface::{ConcreteGraphMut, Id}; use util::splitvec::SplitVec; // ---------------------------------------------------------------- /// Target-node specifier for use with `Builder::append_edge`. #[d...
<E, F>(&mut self, tgt: Target<G::NodeId>, e: E, mut f: F) -> G::NodeId where F: NodeFn<G, E>, (G::NodeId, G::NodeId, E): Into<G::Edge>, E: Clone { match tgt { Target::InputOutput => { for prev in self.inputs.iter() { ...
append_edge
identifier_name
regions-outlives-nominal-type-region-rev.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> { x: fn(&'a i32), } trait Trait<'a, 'b> { type Out; } impl<'a, 'b> Trait<'a, 'b> for usize { type Out = &'a Foo<'b>; //~ ERROR reference has a longer lifetime } } fn main() { }
Foo
identifier_name
regions-outlives-nominal-type-region-rev.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 ...
mod rev_variant_struct_region { struct Foo<'a> { x: fn(&'a i32), } trait Trait<'a, 'b> { type Out; } impl<'a, 'b> Trait<'a, 'b> for usize { type Out = &'a Foo<'b>; //~ ERROR reference has a longer lifetime } } fn main() { }
#![allow(dead_code)]
random_line_split
codec.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <zexavexxe@gmail.com> Copyright © 2017 Roman Proskuryakov <humbug@deeptown.org> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Pu...
channel: Channel } impl Codec { /// create a new Codec with the given Channel pub fn new(channel: Channel) -> Codec { Codec { channel: channel } } } impl Decoder for Codec { type Item = Packet; type Error = Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Ite...
random_line_split
codec.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <zexavexxe@gmail.com> Copyright © 2017 Roman Proskuryakov <humbug@deeptown.org> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Pu...
IResult::Error(e) => { Err(Error::new(ErrorKind::Other, format!("deserialize Packet error: {:?}", e))) }, IResult::Done(_, packet) => { buf.split_to(consumed); Ok(Some(packet)) } } } } impl E...
Err(Error::new(ErrorKind::Other, "Packet should not be incomplete")) },
conditional_block
codec.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <zexavexxe@gmail.com> Copyright © 2017 Roman Proskuryakov <humbug@deeptown.org> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Pu...
{ let (pk, _) = gen_keypair(); let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::new(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let test_packets = vec![ Packet::RouteRequest( R...
code_decode()
identifier_name
codec.rs
/* Copyright (C) 2013 Tox project All Rights Reserved. Copyright © 2017 Zetok Zalbavar <zexavexxe@gmail.com> Copyright © 2017 Roman Proskuryakov <humbug@deeptown.org> This file is part of Tox. Tox is libre software: you can redistribute it and/or modify it under the terms of the GNU General Pu...
#[test] fn decode_packet_error() { let (alice_channel, bob_channel) = create_channels(); let mut alice_codec = Codec::new(alice_channel); let mut bob_codec = Codec::new(bob_channel); let mut buf = BytesMut::new(); // bad Data with connection id = 0x0F let packet...
let (alice_channel, bob_channel) = create_channels(); let mut buf = BytesMut::from(encode_bytes_to_packet(&alice_channel,b"\x00")); let mut bob_codec = Codec::new(bob_channel); // not enought bytes to decode Packet assert!(bob_codec.decode(&mut buf).err().is_some()); }
identifier_body
font.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::{FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, Fraction...
} } } impl FontHandleMethods for FontHandle { fn new_from_template(fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) -> Result<FontHandle, ()> { let ft_ctx: FT_Library = fctx.ctx.ctx; if...
{ panic!("FT_Done_Face failed"); }
conditional_block
font.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::{FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, Fraction...
(&self) -> FontMetrics { /* TODO(Issue #76): complete me */ let face = self.face_rec_mut(); let underline_size = self.font_units_to_au(face.underline_thickness as f64); let underline_offset = self.font_units_to_au(face.underline_position as f64); let em_size = self.font_units_to...
metrics
identifier_name
font.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::{FontHandleMethods, FontMetrics, FontTableMethods}; use font::{FontTableTag, Fraction...
use freetype::tt_os2::TT_OS2; use platform::font_context::FontContextHandle; use platform::font_template::FontTemplateData; use servo_atoms::Atom; use std::{mem, ptr}; use std::os::raw::{c_char, c_long}; use std::sync::Arc; use style::computed_values::font_stretch::T as FontStretch; use style::computed_values::font_wei...
use freetype::freetype::{FT_SizeRec, FT_Size_Metrics, FT_UInt, FT_Vector}; use freetype::freetype::FT_Sfnt_Tag;
random_line_split
issue-25757.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self) { self.a = 5; } } const FUNC: &'static Fn(&mut Foo) -> () = &Foo::x; fn main() { let mut foo = Foo { a: 137 }; FUNC(&mut foo); assert_eq!(foo.a, 5); }
x
identifier_name
issue-25757.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
a: u32 } impl Foo { fn x(&mut self) { self.a = 5; } } const FUNC: &'static Fn(&mut Foo) -> () = &Foo::x; fn main() { let mut foo = Foo { a: 137 }; FUNC(&mut foo); assert_eq!(foo.a, 5); }
// option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass struct Foo {
random_line_split
error.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
error_chain! { types { EntryUtilError, EntryUtilErrorKind, ResultExt, Result; } foreign_links { TomlQueryError(::toml_query::error::Error); } errors { } }
random_line_split
empty-allocation-non-null.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 ...
struct Foo; assert!(Some(Box::new(Foo)).is_some()); let ys: Box<[Foo]> = Box::<[Foo; 0]>::new([]); assert!(Some(ys).is_some()); }
random_line_split
empty-allocation-non-null.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 ...
; assert!(Some(Box::new(Foo)).is_some()); let ys: Box<[Foo]> = Box::<[Foo; 0]>::new([]); assert!(Some(ys).is_some()); }
Foo
identifier_name
method.rs
//! The HTTP request method use std::fmt; use std::str::FromStr; use std::convert::AsRef; use error::Error; use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, Extension}; #[cfg(feature = "serde-serialization")] use serde::{Deserialize, Deserializer, Serialize, Serializ...
} #[cfg(feature = "serde-serialization")] impl Serialize for Method { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer { format!("{}", self).serialize(serializer) } } #[cfg(feature = "serde-serialization")] impl Deserialize for Method { fn deserialize<D>(dese...
{ fmt.write_str(match *self { Options => "OPTIONS", Get => "GET", Post => "POST", Put => "PUT", Delete => "DELETE", Head => "HEAD", Trace => "TRACE", Connect => "CONNECT", Patch => "PATCH", Ex...
identifier_body
method.rs
//! The HTTP request method use std::fmt; use std::str::FromStr; use std::convert::AsRef; use error::Error; use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, Extension}; #[cfg(feature = "serde-serialization")] use serde::{Deserialize, Deserializer, Serialize, Serializ...
} #[cfg(test)] mod tests { use std::collections::HashMap; use std::str::FromStr; use error::Error; use super::Method; use super::Method::{Get, Post, Put, Extension}; #[test] fn test_safe() { assert_eq!(true, Get.safe()); assert_eq!(false, Post.safe()); } #[test] ...
fn deserialize<D>(deserializer: &mut D) -> Result<Method, D::Error> where D: Deserializer { let string_representation: String = try!(Deserialize::deserialize(deserializer)); Ok(FromStr::from_str(&string_representation[..]).unwrap()) }
random_line_split
method.rs
//! The HTTP request method use std::fmt; use std::str::FromStr; use std::convert::AsRef; use error::Error; use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, Extension}; #[cfg(feature = "serde-serialization")] use serde::{Deserialize, Deserializer, Serialize, Serializ...
() { assert_eq!(true, Get.idempotent()); assert_eq!(true, Put.idempotent()); assert_eq!(false, Post.idempotent()); } #[test] fn test_from_str() { assert_eq!(Get, FromStr::from_str("GET").unwrap()); assert_eq!(Extension("MOVE".to_owned()), FromStr::...
test_idempotent
identifier_name
unique-vec-res.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let i1 = &Cell::new(0); let i2 = &Cell::new(1); let r1 = vec!(box r { i: i1 }); let r2 = vec!(box r { i: i2 }); f(clone(&r1), clone(&r2)); //~^ ERROR the trait `core::clone::Clone` is not implemented for the type //~^^ ERROR the trait `core::clone::Clone` is not implemented for the type ...
identifier_body
unique-vec-res.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let r2 = vec!(box r { i: i2 }); f(clone(&r1), clone(&r2)); //~^ ERROR the trait `core::clone::Clone` is not implemented for the type //~^^ ERROR the trait `core::clone::Clone` is not implemented for the type println!("{}", (r2, i1.get())); println!("{}", (r1, i2.get())); }
let i1 = &Cell::new(0); let i2 = &Cell::new(1); let r1 = vec!(box r { i: i1 });
random_line_split
unique-vec-res.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(_i: Vec<T>, _j: Vec<T> ) { } fn clone<T: Clone>(t: &T) -> T { t.clone() } fn main() { let i1 = &Cell::new(0); let i2 = &Cell::new(1); let r1 = vec!(box r { i: i1 }); let r2 = vec!(box r { i: i2 }); f(clone(&r1), clone(&r2)); //~^ ERROR the trait `core::clone::Clone` is not implemented for ...
f
identifier_name
quickchecks.rs
extern crate editdistancewf as wf; extern crate quickcheck; use quickcheck::quickcheck; #[test] fn at_least_size_difference_property()
#[test] fn at_most_length_of_longer_property() { fn at_most_size_of_longer(a: String, b: String) -> bool { let upper_bound = *[a.chars().count(), b.chars().count()] .iter() .max() .unwrap() as usize; wf::distance(a.chars(), b.chars()) <...
{ fn at_least_size_difference(a: String, b: String) -> bool { let size_a = a.chars().count() as isize; let size_b = b.chars().count() as isize; let diff = (size_a - size_b).abs() as usize; wf::distance(a.chars(), b.chars()) >= diff } quickcheck(at_least_size_difference as f...
identifier_body
quickchecks.rs
extern crate editdistancewf as wf; extern crate quickcheck; use quickcheck::quickcheck; #[test] fn at_least_size_difference_property() { fn at_least_size_difference(a: String, b: String) -> bool { let size_a = a.chars().count() as isize; let size_b = b.chars().count() as isize; let diff = (...
else { d > 0 } } quickcheck(zero_iff_a_equals_b as fn(a: String, b: String) -> bool); } #[test] fn triangle_inequality_property() { fn triangle_inequality(a: String, b: String, c: String) -> bool { wf::distance(a.chars(), b.chars()) <= wf::distance(a.chars(), c.cha...
{ d == 0 }
conditional_block
quickchecks.rs
extern crate editdistancewf as wf; extern crate quickcheck; use quickcheck::quickcheck; #[test] fn
() { fn at_least_size_difference(a: String, b: String) -> bool { let size_a = a.chars().count() as isize; let size_b = b.chars().count() as isize; let diff = (size_a - size_b).abs() as usize; wf::distance(a.chars(), b.chars()) >= diff } quickcheck(at_least_size_difference a...
at_least_size_difference_property
identifier_name
quickchecks.rs
extern crate editdistancewf as wf; extern crate quickcheck; use quickcheck::quickcheck; #[test] fn at_least_size_difference_property() { fn at_least_size_difference(a: String, b: String) -> bool { let size_a = a.chars().count() as isize; let size_b = b.chars().count() as isize; let diff = (...
wf::distance(a.chars(), c.chars()) + wf::distance(b.chars(), c.chars()) } quickcheck(triangle_inequality as fn(a: String, b: String, c: String) -> bool); }
fn triangle_inequality(a: String, b: String, c: String) -> bool { wf::distance(a.chars(), b.chars()) <=
random_line_split
day14.rs
extern crate crypto; use std::collections::HashMap; use crypto::md5::Md5; use crypto::digest::Digest; struct HashCache<'a> { base: String, hashes: HashMap<String, String>, hasher: &'a Fn(&str) -> String, } impl<'a> HashCache<'a> { fn new(base: &str, f: &'a Fn(&str) -> String) -> Self { HashCa...
() { let keys = find_keys("jlmsuwbz", 64, &h1); println!("1: {}", keys.last().unwrap().0); let keys = find_keys("jlmsuwbz", 64, &h2016); println!("2: {}", keys.last().unwrap().0); }
main
identifier_name
day14.rs
extern crate crypto; use std::collections::HashMap; use crypto::md5::Md5; use crypto::digest::Digest; struct HashCache<'a> { base: String, hashes: HashMap<String, String>, hasher: &'a Fn(&str) -> String, } impl<'a> HashCache<'a> { fn new(base: &str, f: &'a Fn(&str) -> String) -> Self { HashCa...
if let Some(t) = has_triple(&key) { for i in 1..1000 { if hc.get(index + i).contains(&t) { ret.push((index, key)); break } } } index += 1; } ret } fn h1(salt: &str) -> String { let mut ...
while ret.len() < num_keys { let key = hc.get(index);
random_line_split
day14.rs
extern crate crypto; use std::collections::HashMap; use crypto::md5::Md5; use crypto::digest::Digest; struct HashCache<'a> { base: String, hashes: HashMap<String, String>, hasher: &'a Fn(&str) -> String, } impl<'a> HashCache<'a> { fn new(base: &str, f: &'a Fn(&str) -> String) -> Self { HashCa...
} } index += 1; } ret } fn h1(salt: &str) -> String { let mut hasher = Md5::new(); hasher.input(salt.as_bytes()); hasher.result_str() } fn h2016(salt: &str) -> String { let mut hasher = Md5::new(); let mut key = h1(salt); for _ in 0..2016 { hasher...
{ ret.push((index, key)); break }
conditional_block
day14.rs
extern crate crypto; use std::collections::HashMap; use crypto::md5::Md5; use crypto::digest::Digest; struct HashCache<'a> { base: String, hashes: HashMap<String, String>, hasher: &'a Fn(&str) -> String, } impl<'a> HashCache<'a> { fn new(base: &str, f: &'a Fn(&str) -> String) -> Self { HashCa...
fn find_keys(salt: &str, num_keys: usize, hasher: &Fn(&str) -> String) -> Vec<(usize, String)> { let mut ret = Vec::new(); let mut index = 0; let mut hc = HashCache::new(salt, hasher); while ret.len() < num_keys { let key = hc.get(index); if let Some(t) = has_triple(&key) { ...
{ let v : Vec<_> = key.chars().collect(); let mut windows = v.windows(3); while let Some(x) = windows.next() { let (a, b, c) = (x[0], x[1], x[2]); if a == b && b == c { return Some(format!("{}{}{}{}{}", a, a, a, a, a)) } } None }
identifier_body
inefficient_to_string.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_type_diagnostic_item, walk_ptrs_ty_depth}; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateCont...
/// Returns whether `ty` specializes `ToString`. /// Currently, these are `str`, `String`, and `Cow<'_, str>`. fn specializes_tostring(cx: &LateContext<'_>, ty: Ty<'_>) -> bool { if let ty::Str = ty.kind() { return true; } if is_type_diagnostic_item(cx, ty, sym::String) { return true; }...
random_line_split
inefficient_to_string.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_type_diagnostic_item, walk_ptrs_ty_depth}; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateCont...
<'tcx>(cx: &LateContext<'tcx>, expr: &hir::Expr<'_>, method_name: Symbol, args: &[hir::Expr<'_>]) { if_chain! { if args.len() == 1 && method_name == sym!(to_string); if let Some(to_string_meth_did) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, to_string_meth...
check
identifier_name
inefficient_to_string.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_type_diagnostic_item, walk_ptrs_ty_depth}; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateCont...
else { false } }
{ match_def_path(cx, adt.did, &paths::COW) && substs.type_at(1).is_str() }
conditional_block
inefficient_to_string.rs
use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet_with_applicability; use clippy_utils::ty::{is_type_diagnostic_item, walk_ptrs_ty_depth}; use clippy_utils::{match_def_path, paths}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::LateCont...
self_ty, deref_self_ty )); let mut applicability = Applicability::MachineApplicable; let arg_snippet = snippet_with_applicability(cx, args[0].span, "..", &mut applicability); diag.span_suggestion( ...
{ if_chain! { if args.len() == 1 && method_name == sym!(to_string); if let Some(to_string_meth_did) = cx.typeck_results().type_dependent_def_id(expr.hir_id); if match_def_path(cx, to_string_meth_did, &paths::TO_STRING_METHOD); if let Some(substs) = cx.typeck_results().node_substs_opt...
identifier_body
sqrt.rs
use {Style, Sign, Float}; impl Float { pub fn sqrt(mut self) -> Float { self.debug_assert_valid(); let prec = self.prec; match self.style { Style::NaN => Float::nan(prec), Style::Infinity => { match self.sign { Sign::Pos => Float:...
if self.sign == Sign::Neg { return Float::nan(prec); } // use this instead of % 2 to get the right sign // (should be 0 or 1, even if exp is negative) let c = self.exp & 1; let exp = (self.exp - c) / 2; ...
Sign::Neg => Float::nan(prec), } } Style::Zero => Float::zero_(prec, self.sign), Style::Normal => {
random_line_split
sqrt.rs
use {Style, Sign, Float}; impl Float { pub fn sqrt(mut self) -> Float
let c = self.exp & 1; let exp = (self.exp - c) / 2; // we compute sqrt(m1 * 2**c * 2**(p + 1)) to ensure // we get the full significand, and the rounding bit, // and can use the remainder to check for sticky bits. let shift...
{ self.debug_assert_valid(); let prec = self.prec; match self.style { Style::NaN => Float::nan(prec), Style::Infinity => { match self.sign { Sign::Pos => Float::inf(prec, Sign::Pos), Sign::Neg => Float::nan(prec), ...
identifier_body
sqrt.rs
use {Style, Sign, Float}; impl Float { pub fn
(mut self) -> Float { self.debug_assert_valid(); let prec = self.prec; match self.style { Style::NaN => Float::nan(prec), Style::Infinity => { match self.sign { Sign::Pos => Float::inf(prec, Sign::Pos), Sign::Neg =>...
sqrt
identifier_name
newlambdas.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn ff() -> @fn(int) -> int { return |x| x + 1; } pub fn main() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(do f(10) |a| { a }, 10); do g() { } let _x: @fn() -> int = || 10; let _y: @fn(int) -> int = |a| a; assert_eq!(ff()(10), 11); }
// Tests for the new |args| expr lambda syntax fn f(i: int, f: &fn(int) -> int) -> int { f(i) } fn g(g: &fn()) { }
random_line_split
newlambdas.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(g: &fn()) { } fn ff() -> @fn(int) -> int { return |x| x + 1; } pub fn main() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(do f(10) |a| { a }, 10); do g() { } let _x: @fn() -> int = || 10; let _y: @fn(int) -> int = |a| a; assert_eq!(ff()(10), 11); }
g
identifier_name
newlambdas.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn ff() -> @fn(int) -> int { return |x| x + 1; } pub fn main() { assert_eq!(f(10, |a| a), 10); g(||()); assert_eq!(do f(10) |a| { a }, 10); do g() { } let _x: @fn() -> int = || 10; let _y: @fn(int) -> int = |a| a; assert_eq!(ff()(10), 11); }
{ }
identifier_body
p051.rs
//! [Problem 51](https://projecteuler.net/problem=51) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate integer; extern crate prime; use integer::Integer; use prime::PrimeSet; ...
problem!("121313", solve); #[cfg(test)] mod tests { #[test] fn seven() { assert_eq!(56003, super::compute(7)) } }
{ compute(8).to_string() }
identifier_body
p051.rs
//! [Problem 51](https://projecteuler.net/problem=51) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate integer; extern crate prime; use integer::Integer; use prime::PrimeSet; ...
() { assert_eq!(56003, super::compute(7)) } }
seven
identifier_name
p051.rs
//! [Problem 51](https://projecteuler.net/problem=51) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate integer; extern crate prime; use integer::Integer; use prime::PrimeSet; ...
} } } unreachable!() } fn solve() -> String { compute(8).to_string() } problem!("121313", solve); #[cfg(test)] mod tests { #[test] fn seven() { assert_eq!(56003, super::compute(7)) } }
} if num_prime >= num_value { return p
random_line_split
p051.rs
//! [Problem 51](https://projecteuler.net/problem=51) solver. #![warn(bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results)] #[macro_use(problem)] extern crate common; extern crate integer; extern crate prime; use integer::Integer; use prime::PrimeSet; ...
} if num_prime >= num_value { return p } } } unreachable!() } fn solve() -> String { compute(8).to_string() } problem!("121313", solve); #[cfg(test)] mod tests { #[test] fn seven() { assert_eq!(56003, super::compute(7)) } }
{ num_prime += 1; }
conditional_block
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. extern crate core_foundation; extern crate core_graphics; exte...
(&self, glyph: GlyphId) -> Option<FractionalPixel> { let glyphs = [glyph as CGGlyph]; let advance = self.ctfont.get_advances_for_glyphs(kCTFontDefaultOrientation, &glyphs[0], ptr::null_mut...
glyph_h_advance
identifier_name
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. extern crate core_foundation; extern crate core_graphics; exte...
fn stretchiness(&self) -> font_stretch::T { let normalized = self.ctfont.all_traits().normalized_width(); // [-1.0, 1.0] let normalized = (normalized + 1.0) / 2.0 * 9.0; // [0.0, 9.0] match normalized { v if v < 1.0 => font_stretch::T::ultra_condensed, v if v < 2.0...
v if v < 8.0 => font_weight::T::Weight800, _ => font_weight::T::Weight900, } }
random_line_split
font.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/. */ /// Implementation of Quartz (CoreGraphics) fonts. extern crate core_foundation; extern crate core_graphics; exte...
} #[derive(Debug)] pub struct FontHandle { pub font_data: Arc<FontTemplateData>, pub ctfont: CTFont, } impl FontHandleMethods for FontHandle { fn new_from_template(_fctx: &FontContextHandle, template: Arc<FontTemplateData>, pt_size: Option<Au>) ...
{ blk(self.data.bytes().as_ptr(), self.data.len() as usize); }
identifier_body
htmlbrelement.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::HTMLBRElementBinding; use dom::bindings::root::DomRoot; use dom::document::D...
impl HTMLBRElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLBRElement { HTMLBRElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalNam...
}
random_line_split
htmlbrelement.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::HTMLBRElementBinding; use dom::bindings::root::DomRoot; use dom::document::D...
(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLBRElement> { Node::reflect_node(Box::new(HTMLBRElement::new_inherited(local_name, prefix, document)), document, HTMLBRElementBinding::Wrap) ...
new
identifier_name
issue-3743.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 ...
// Vec2's implementation of Mul "from the other side" using the above trait impl<Res, Rhs: RhsOfVec2Mul<Res>> Mul<Rhs,Res> for Vec2 { fn mul(&self, rhs: &Rhs) -> Res { rhs.mul_vec2_by(self) } } // Implementation of 'f64 as right-hand-side of Vec2::Mul' impl RhsOfVec2Mul<Vec2> for f64 { fn mul_vec2_by(&self, l...
// Right-hand-side operator visitor pattern trait RhsOfVec2Mul<Result> { fn mul_vec2_by(&self, lhs: &Vec2) -> Result; }
random_line_split
issue-3743.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 a = Vec2 { x: 3.0f64, y: 4.0f64 }; // the following compiles and works properly let v1: Vec2 = a * 3.0f64; println!("{} {}", v1.x, v1.y); // the following compiles but v2 will not be Vec2 yet and // using it later will cause an error that the type of v2 // must be known let v2...
main
identifier_name
borrowck-preserve-box-in-uniq.rs
// xfail-pretty // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license //...
{ let mut x = ~@F{f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); *x = @F{f: ~4}; info!("ptr::to_unsafe_ptr(*b_x) = {:x}", ptr::to_unsafe_ptr(&(*b_x)) as uint); assert_eq!(*b_x, 3); ...
identifier_body
borrowck-preserve-box-in-uniq.rs
// xfail-pretty // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license //...
ptr::to_unsafe_ptr(&(*b_x)) as uint); assert_eq!(*b_x, 3); assert!(ptr::to_unsafe_ptr(&(*x.f))!= ptr::to_unsafe_ptr(&(*b_x))); }) }
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
random_line_split
borrowck-preserve-box-in-uniq.rs
// xfail-pretty // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license //...
{ f: ~int } pub fn main() { let mut x = ~@F{f: ~3}; borrow(x.f, |b_x| { assert_eq!(*b_x, 3); assert_eq!(ptr::to_unsafe_ptr(&(*x.f)), ptr::to_unsafe_ptr(&(*b_x))); *x = @F{f: ~4}; info!("ptr::to_unsafe_ptr(*b_x) = {:x}", ptr::to_unsafe_ptr(&(*b_x)) as uint); ...
F
identifier_name
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use fnv::FnvHashMap; use graphql_ir::{build, Program}; use graphql_syntax::parse; ...
} } else { panic!("Expected exactly one %extensions% section marker.") } }
{ let mut errs = errors .into_iter() .map(|err| err.print(&sources)) .collect::<Vec<_>>(); errs.sort(); Err(errs.join("\n\n")) }
conditional_block
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use fnv::FnvHashMap; use graphql_ir::{build, Program}; use graphql_syntax::parse; ...
.collect::<Vec<_>>(); errs.sort(); Err(errs.join("\n\n")) } } } else { panic!("Expected exactly one %extensions% section marker.") } }
{ let parts: Vec<_> = fixture.content.split("%extensions%").collect(); if let [base, extensions] = parts.as_slice() { let file_key = FileKey::new(fixture.file_name); let ast = parse(base, file_key).unwrap(); let schema = test_schema_with_extensions(extensions); let mut sources =...
identifier_body
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use fnv::FnvHashMap; use graphql_ir::{build, Program}; use graphql_syntax::parse;
if let [base, extensions] = parts.as_slice() { let file_key = FileKey::new(fixture.file_name); let ast = parse(base, file_key).unwrap(); let schema = test_schema_with_extensions(extensions); let mut sources = FnvHashMap::default(); sources.insert(FileKey::new(fixture.file_na...
use graphql_transforms::validate_server_only_directives; use test_schema::test_schema_with_extensions; pub fn transform_fixture(fixture: &Fixture) -> Result<String, String> { let parts: Vec<_> = fixture.content.split("%extensions%").collect();
random_line_split
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::FileKey; use fixture_tests::Fixture; use fnv::FnvHashMap; use graphql_ir::{build, Program}; use graphql_syntax::parse; ...
(fixture: &Fixture) -> Result<String, String> { let parts: Vec<_> = fixture.content.split("%extensions%").collect(); if let [base, extensions] = parts.as_slice() { let file_key = FileKey::new(fixture.file_name); let ast = parse(base, file_key).unwrap(); let schema = test_schema_with_ext...
transform_fixture
identifier_name
cache.rs
// This module defines a common API for caching internal runtime state. // The `thread_local` crate provides an extremely optimized version of this. // However, if the perf-cache feature is disabled, then we drop the // thread_local dependency and instead use a pretty naive caching mechanism // with a mutex. // // Stri...
pub use self::imp::{Cached, CachedGuard}; #[cfg(feature = "perf-cache")] mod imp { use thread_local::CachedThreadLocal; #[derive(Debug)] pub struct Cached<T: Send>(CachedThreadLocal<T>); #[derive(Debug)] pub struct CachedGuard<'a, T: 'a>(&'a T); impl<T: Send> Cached<T> { pub fn new(...
// flexible thread_local API, but implementing thread_local's API doesn't // seem possible in purely safe code.
random_line_split
cache.rs
// This module defines a common API for caching internal runtime state. // The `thread_local` crate provides an extremely optimized version of this. // However, if the perf-cache feature is disabled, then we drop the // thread_local dependency and instead use a pretty naive caching mechanism // with a mutex. // // Stri...
(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { CachedGuard(self.0.get_or(|| create())) } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.0 } } } #[cfg(not(feature = "perf-cache"))] mod imp { use std::marker::PhantomData...
get_or
identifier_name
cache.rs
// This module defines a common API for caching internal runtime state. // The `thread_local` crate provides an extremely optimized version of this. // However, if the perf-cache feature is disabled, then we drop the // thread_local dependency and instead use a pretty naive caching mechanism // with a mutex. // // Stri...
pub fn get_or(&self, create: impl FnOnce() -> T) -> CachedGuard<T> { CachedGuard(self.0.get_or(|| create())) } } impl<'a, T: Send> CachedGuard<'a, T> { pub fn value(&self) -> &T { self.0 } } } #[cfg(not(feature = "perf-cache"))] mod imp { use s...
{ Cached(CachedThreadLocal::new()) }
identifier_body
cache.rs
// This module defines a common API for caching internal runtime state. // The `thread_local` crate provides an extremely optimized version of this. // However, if the perf-cache feature is disabled, then we drop the // thread_local dependency and instead use a pretty naive caching mechanism // with a mutex. // // Stri...
} } }
{ self.cache.put(value); }
conditional_block
font.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/. */ extern mod freetype; use font::{CSSFontWeight, FontHandleMethods, FontMetrics, FontTableMethods}; use font::{Font...
} enum FontSource { FontSourceMem(~[u8]), FontSourceFile(~str) } pub struct FontHandle { // The font binary. This must stay valid for the lifetime of the font, // if the font is created using FT_Memory_Face. source: FontSource, face: FT_Face, handle: FontContextHandle } #[unsafe_destruct...
{ fail!() }
identifier_body
font.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/. */ extern mod freetype; use font::{CSSFontWeight, FontHandleMethods, FontMetrics, FontTableMethods}; use font::{Font...
(&self, fctx: &FontContextHandle, style: &UsedFontStyle) -> Result<FontHandle, ()> { match self.source { FontSourceMem(ref buf) => { FontHandleMethods::new_from_buffer(fctx, buf.clone(), style) } FontSourceFile(r...
clone_with_style
identifier_name
font.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/. */ extern mod freetype; use font::{CSSFontWeight, FontHandleMethods, FontMetrics, FontTableMethods}; use font::{Font...
} } return FontMetrics { underline_size: underline_size, underline_offset: underline_offset, strikeout_size: strikeout_size, strikeout_offset: strikeout_offset, leading: geometry::from_pt(0.0), //FIXME x_he...
strikeout_size = self.font_units_to_au((*os2).yStrikeoutSize as float); strikeout_offset = self.font_units_to_au((*os2).yStrikeoutPosition as float); x_height = self.font_units_to_au((*os2).sxHeight as float);
random_line_split
font.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/. */ extern mod freetype; use font::{CSSFontWeight, FontHandleMethods, FontMetrics, FontTableMethods}; use font::{Font...
} } } fn clone_with_style(&self, fctx: &FontContextHandle, style: &UsedFontStyle) -> Result<FontHandle, ()> { match self.source { FontSourceMem(ref buf) => { FontHandleMethods::new_from_buffer(fctx, buf.clo...
{ default_weight }
conditional_block
move_cell.rs
//! A cell type that can move values into and out of a shared reference. //! //! Behaves like `RefCell<Option<T>>` but optimized for use-cases where temporary or permanent //! ownership is required. use std::cell::UnsafeCell; use std::mem; /// A cell type that can move values into and out of a shared reference. pub s...
}
{ MoveCell::new() }
identifier_body
move_cell.rs
//! A cell type that can move values into and out of a shared reference. //! //! Behaves like `RefCell<Option<T>>` but optimized for use-cases where temporary or permanent //! ownership is required. use std::cell::UnsafeCell; use std::mem; /// A cell type that can move values into and out of a shared reference. pub s...
(&self) -> &Option<T> { & *self.0.get() } /// Place a value into this `MoveCell`, returning the previous value, if present. pub fn put(&self, val: T) -> Option<T> { mem::replace(unsafe { self.as_mut() }, Some(val)) } /// Take the value out of this `MoveCell`, leaving nothing...
as_ref
identifier_name
move_cell.rs
//! A cell type that can move values into and out of a shared reference. //! //! Behaves like `RefCell<Option<T>>` but optimized for use-cases where temporary or permanent //! ownership is required. use std::cell::UnsafeCell; use std::mem; /// A cell type that can move values into and out of a shared reference. pub s...
} unsafe fn as_ref(&self) -> &Option<T> { & *self.0.get() } /// Place a value into this `MoveCell`, returning the previous value, if present. pub fn put(&self, val: T) -> Option<T> { mem::replace(unsafe { self.as_mut() }, Some(val)) } /// Take the value out of this ...
&mut *self.0.get()
random_line_split
util.rs
use std::fmt; use std::io::{IoErrorKind, IoResult}; #[derive(Copy)] pub struct FormatBytes(pub u64); impl FormatBytes { #[inline] fn to_kb(self) -> f64 { (self.0 as f64) / 1.0e3 } #[inline] fn to_mb(self) -> f64 { (self.0 as f64) / 1.0e6 } #[inline] fn to_gb(self)...
FormatTime(hours, minutes, seconds) } } impl fmt::String for FormatTime { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { f.write_fmt(format_args!("{}:{:02}:{:02}", self.0, self.1, self.2)) } }
let minutes = (tot_min % 60) as u8; let hours = tot_min / 60;
random_line_split
util.rs
use std::fmt; use std::io::{IoErrorKind, IoResult}; #[derive(Copy)] pub struct FormatBytes(pub u64); impl FormatBytes { #[inline] fn to_kb(self) -> f64 { (self.0 as f64) / 1.0e3 } #[inline] fn to_mb(self) -> f64 { (self.0 as f64) / 1.0e6 } #[inline] fn to_gb(self)...
(pub u64, pub u8, pub u8); impl FormatTime { pub fn from_s(s: u64) -> FormatTime { let seconds = (s % 60) as u8; let tot_min = s / 60; let minutes = (tot_min % 60) as u8; let hours = tot_min / 60; FormatTime(hours, minutes, seconds) } } impl f...
FormatTime
identifier_name
perm.rs
use centrifuge::{Store, Message}; pub struct PermStore<'a> { sequence: usize, position: usize, data: &'a mut [u8] } #[derive(Debug)] pub struct PermMsg<'a> { sequence: usize, data: &'a [u8], } impl <'a> PermStore<'a> { pub fn new(data: &'a mut [u8]) -> Self { PermStore { ...
#[inline] fn get_remaining_slice(&mut self) -> &'a mut [u8] { let start = self.position; let end = self.data.len(); self.get_slice_from_to(start, end) } } impl <'a> Message for PermMsg<'a> { fn get_sequence(&self) -> usize { self.sequence } fn get_data(&self) -...
{ self.get_slice(from, to - from) }
identifier_body
perm.rs
use centrifuge::{Store, Message}; pub struct PermStore<'a> { sequence: usize, position: usize, data: &'a mut [u8] } #[derive(Debug)] pub struct PermMsg<'a> { sequence: usize, data: &'a [u8], } impl <'a> PermStore<'a> { pub fn new(data: &'a mut [u8]) -> Self { PermStore { ...
let pos = self.position; PermMsg { sequence: seq, data: self.get_slice_from_to(start, pos) } } } #[cfg(test)] pub mod test { use centrifuge::*; #[test] pub fn test_perm() { use centrifuge::perm::*; let mut sequence_nums = Vec...
self.sequence += 1; let seq = self.sequence;
random_line_split
perm.rs
use centrifuge::{Store, Message}; pub struct PermStore<'a> { sequence: usize, position: usize, data: &'a mut [u8] } #[derive(Debug)] pub struct PermMsg<'a> { sequence: usize, data: &'a [u8], } impl <'a> PermStore<'a> { pub fn
(data: &'a mut [u8]) -> Self { PermStore { sequence: 0, position: 0, data: data } } #[inline] fn get_slice(&mut self, from: usize, len: usize) -> &'a mut [u8] { use std::slice::from_raw_parts_mut; let ptr = self.data.as_mut_ptr(); ...
new
identifier_name
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
impl<'a, W: Writer> RepeatFasta<'a, W> { fn new(alu: &'static str, w: &'a mut W) -> RepeatFasta<'a, W> { RepeatFasta { alu: alu, out: w } } fn make(&mut self, n: uint) -> IoResult<()> { let alu_len = self.alu.len(); let mut buf = Vec::from_elem(alu_len + LINE_LEN, 0u8); let ...
alu: &'static str, out: &'a mut W }
random_line_split
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
(&mut self, max: f32) -> f32 { self.seed = (self.seed * IA + IC) % IM; max * (self.seed as f32) / (IM as f32) } fn nextc(&mut self) -> u8 { let r = self.rng(1.0); for a in self.lookup.iter() { if a.p >= r { return a.c; } } ...
rng
identifier_name
shootout-fasta-redux.rs
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // contributed by the Rust Project Developers // Copyright (c) 2013-2014 The Rust Project Developers // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted...
} 0 } fn make(&mut self, n: uint) -> IoResult<()> { let lines = n / LINE_LEN; let chars_left = n % LINE_LEN; let mut buf = [0,..LINE_LEN + 1]; for _ in range(0, lines) { for i in range(0u, LINE_LEN) { buf[i] = self.nextc(); ...
{ return a.c; }
conditional_block
pipe_unix.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 accept(&mut self) -> IoResult<Box<rtio::RtioPipe:Send>> { self.native_accept().map(|s| box s as Box<rtio::RtioPipe:Send>) } fn set_timeout(&mut self, timeout: Option<u64>) { self.deadline = timeout.map(|a| ::io::timer::now() + a).unwrap_or(0); } } impl Drop for UnixListener { fn ...
} } impl rtio::RtioUnixAcceptor for UnixAcceptor {
random_line_split
pipe_unix.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 ...
(addr: &CString, timeout: Option<u64>) -> IoResult<UnixStream> { connect(addr, libc::SOCK_STREAM, timeout).map(|inner| { UnixStream::new(Arc::new(inner)) }) } fn new(inner: Arc<Inner>) -> UnixStream { UnixStream { inner: inner, read...
connect
identifier_name
bytevec.rs
use std::fmt::Debug; use std::{fmt, ops}; /// Wrapper around `Vec<u8>` for efficient `AlgoIo` conversions when working with byte data /// /// Serde JSON serializes/deserializes `Vec<u8>` as an array of numbers. /// This type provides a more direct way of converting to/from `AlgoIo` without going through JSON. #[derive...
(&self) -> &[u8] { &self.bytes[..] } } impl ops::DerefMut for ByteVec { fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..] } }
deref
identifier_name
bytevec.rs
use std::fmt::Debug; use std::{fmt, ops}; /// Wrapper around `Vec<u8>` for efficient `AlgoIo` conversions when working with byte data /// /// Serde JSON serializes/deserializes `Vec<u8>` as an array of numbers. /// This type provides a more direct way of converting to/from `AlgoIo` without going through JSON. #[derive...
} impl Debug for ByteVec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { Debug::fmt(&self.bytes, f) } } impl From<ByteVec> for Vec<u8> { fn from(wrapper: ByteVec) -> Vec<u8> { wrapper.bytes } } impl From<Vec<u8>> for ByteVec { fn from(bytes: Vec<u8>) -> Self { Byt...
pub fn from<T: Into<Vec<u8>>>(bytes: T) -> Self { ByteVec { bytes: bytes.into(), } }
random_line_split
bytevec.rs
use std::fmt::Debug; use std::{fmt, ops}; /// Wrapper around `Vec<u8>` for efficient `AlgoIo` conversions when working with byte data /// /// Serde JSON serializes/deserializes `Vec<u8>` as an array of numbers. /// This type provides a more direct way of converting to/from `AlgoIo` without going through JSON. #[derive...
} impl AsMut<Vec<u8>> for ByteVec { fn as_mut(&mut self) -> &mut Vec<u8> { &mut self.bytes } } impl AsMut<[u8]> for ByteVec { fn as_mut(&mut self) -> &mut [u8] { &mut self.bytes } } impl ops::Deref for ByteVec { type Target = [u8]; fn deref(&self) -> &[u8] { &self.by...
{ &self.bytes }
identifier_body
main.rs
extern crate meltdown; extern crate url; extern crate gtk; use url::Url; use std::thread; use std::path::Path; use std::ffi::OsStr; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use gtk::prelude::*; use gtk::Builder; use gtk::MessageDialog; use meltdown::{manager, join_part_files, config}; pub enum UIM...
.max_connection(configurations.max_connection) .file(&file_name) .finish(); let complete_name = file_name.clone(); let (tx, rx) = channel(); let main_tx_clone = main_tx.clone(); let _ = thread::spawn(move || { match manager.start(rx) ...
{ let _ = config::setup_config_directories(); let configurations = config::read_config(); let url_vec = url_vec.split("\n").collect::<Vec<&str>>(); let submitted_tasks = url_vec.len(); let (main_tx, main_rx) = channel(); for url in url_vec { let prefix = config::default_cache_dir().unwr...
identifier_body
main.rs
extern crate meltdown; extern crate url; extern crate gtk; use url::Url; use std::thread; use std::path::Path; use std::ffi::OsStr; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use gtk::prelude::*; use gtk::Builder; use gtk::MessageDialog; use meltdown::{manager, join_part_files, config}; pub enum
{ Finished, Paused, Aborted } fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK."); return; } let glade_src = include_str!("meltdown_ui.glade"); let builder = Builder::new(); builder.add_from_string(glade_src).unwrap(); let window: gtk::Windo...
UIMessage
identifier_name
main.rs
extern crate meltdown; extern crate url; extern crate gtk; use url::Url; use std::thread; use std::path::Path; use std::ffi::OsStr; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use gtk::prelude::*; use gtk::Builder; use gtk::MessageDialog; use meltdown::{manager, join_part_files, config}; pub enum UIM...
Aborted } fn main() { if gtk::init().is_err() { println!("Failed to initialize GTK."); return; } let glade_src = include_str!("meltdown_ui.glade"); let builder = Builder::new(); builder.add_from_string(glade_src).unwrap(); let window: gtk::Window = builder.get_object("windo...
Finished, Paused,
random_line_split
main.rs
extern crate meltdown; extern crate url; extern crate gtk; use url::Url; use std::thread; use std::path::Path; use std::ffi::OsStr; use std::sync::mpsc::channel; use std::sync::mpsc::Sender; use gtk::prelude::*; use gtk::Builder; use gtk::MessageDialog; use meltdown::{manager, join_part_files, config}; pub enum UIM...
}; let url_path_vec = download_url.path_segments().unwrap().collect::<Vec<&str>>(); let file_name = url_path_vec[url_path_vec.len() - 1].to_owned(); manager.add_url(download_url.clone()) .max_connection(configurations.max_connection) .file(&file_name) ...
{ println!("{:?} is not a valid Url", url); continue }
conditional_block
associated-types-eq-hr.rs
// Check testing of equality constraints in a higher-ranked context. pub trait TheTrait<T> { type A; fn get(&self, t: T) -> Self::A; } struct IntStruct { x: isize, } impl<'a> TheTrait<&'a isize> for IntStruct { type A = &'a isize; fn get(&self, t: &'a isize) -> &'a isize { t } } st...
fn tuple_two<T>() where T: for<'x, 'y> TheTrait<(&'x isize, &'y isize), A = &'y isize>, { // not ok for tuple, two lifetimes and we pick second } fn tuple_three<T>() where T: for<'x> TheTrait<(&'x isize, &'x isize), A = &'x isize>, { // ok for tuple } fn tuple_four<T>() where T: for<'x, 'y> TheT...
{ // not ok for tuple, two lifetimes and we pick first }
identifier_body