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
database.rs
extern crate rusqlite; use std::result::Result; use std::string::String; // TODO: use rusqlite::Connection pub struct Database { conn: rusqlite::Connection, } #[derive(Debug)] pub struct Artist { pub id: i32, pub name: String, pub musicbrainz_id: String, pub last_checked: i64 } impl Database { ...
); Ok(()) } pub fn get_least_recently_checked_artist(&self) -> Result<Artist, rusqlite::Error> { let mut stmt = self.conn.prepare("SELECT id, name, musicbrainzId, lastChecked FROM artists ORDER BY lastChecked ASC LIMIT 1").unwrap(); let mut artist_iter = stmt.query_map(&[], |row...
random_line_split
local_ptr.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 ...
<T>(sched: ~T) { RT_TLS_PTR = cast::transmute(sched) } /// Take ownership of a pointer from thread-local storage. /// /// # Safety note /// /// Does not validate the pointer type. #[inline(never)] // see comments above pub unsafe fn take<T>() -> ~T { let ptr = RT_TLS_PTR...
put
identifier_name
local_ptr.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 ...
} /// Borrow the thread-local value from thread-local storage. /// While the value is borrowed it is not available in TLS. /// /// # Safety note /// /// Does not validate the pointer type. #[inline] pub unsafe fn borrow<T>() -> Borrowed<T> { let val: *() = cast::transmute(take::<T>()); Borrowed { val: ...
let val_ptr: &'a mut T = *val_ptr; val_ptr } }
random_line_split
local_ptr.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 ...
pub unsafe fn cleanup() {} // Rationale for all of these functions being inline(never) // // The #[thread_local] annotation gets propagated all the way through to // LLVM, meaning the global is specially treated by LLVM to lower it to an // efficient sequence of instructions. This also involv...
{}
identifier_body
uart_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Lionel Flandrin <lionel@svkt.org> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENS...
} if!sub.expect_attributes(cx, &[("mode", node::StrAttribute)]) { return } let mode = sub.get_string_attr("mode").unwrap(); let mode_re = Regex::new(r"([[:digit:]]+),?([[:digit:]]*)([nNoOEe]?)([[:digit:]])?").unwrap(); let mode_captures = match mode_re.captures(mode.as_slice()) { Some(c) => ...
{ let error = |&: err: &str | { cx.parse_sess().span_diagnostic.span_err(sub.path_span, err); }; let uart_peripheral_str = format!("Uart{}", match sub.path.as_slice().parse::<usize>().unwrap() { 0 ... 7 => sub.path.clone(), p => { error(format!("unknown UART `{}`, allowe...
identifier_body
uart_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Lionel Flandrin <lionel@svkt.org> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENS...
(builder: &mut Builder, cx: &mut ExtCtxt, sub: Rc<node::Node>) { let error = |&: err: &str | { cx.parse_sess().span_diagnostic.span_err(sub.path_span, err); }; let uart_peripheral_str = format!("Uart{}", match sub.path.as_slice().parse::<usize>().unwrap() { 0...
build_uart
identifier_name
uart_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Lionel Flandrin <lionel@svkt.org> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENS...
sub.set_type_name("zinc::hal::tiva_c::uart::Uart".to_string()); let uart_name = TokenString(sub.name.clone().unwrap()); let st = quote_stmt!(&*cx, let $uart_name = zinc::hal::tiva_c::uart::Uart::new( zinc::hal::tiva_c::uart::UartId::$uart_peripheral, $baud_rate, $word_len, ...
random_line_split
async2.rs
// compile-flags: --edition=2018 use core::{ future::Future, marker::Send, pin::Pin, }; fn non_async_func() { println!("non_async_func was covered"); let b = true; if b { println!("non_async_func println in block"); } } async fn async_func() { println!("async_func was cover...
use core::{ future::Future, pin::Pin, task::{Context, Poll, RawWaker, RawWakerVTable, Waker}, }; pub fn block_on<F: Future>(mut future: F) -> F::Output { let mut future = unsafe { Pin::new_unchecked(&mut future) }; use std::hint::unreachable_unchecked; static...
executor::block_on(async_func_just_println()); } mod executor {
random_line_split
async2.rs
// compile-flags: --edition=2018 use core::{ future::Future, marker::Send, pin::Pin, }; fn non_async_func() { println!("non_async_func was covered"); let b = true; if b { println!("non_async_func println in block"); } } async fn async_func() { println!("async_func was cover...
() { println!("async_func_just_println was covered"); } fn main() { println!("codecovsample::main"); non_async_func(); executor::block_on(async_func()); executor::block_on(async_func_just_println()); } mod executor { use core::{ future::Future, pin::Pin, task::{Contex...
async_func_just_println
identifier_name
async2.rs
// compile-flags: --edition=2018 use core::{ future::Future, marker::Send, pin::Pin, }; fn non_async_func() { println!("non_async_func was covered"); let b = true; if b { println!("non_async_func println in block"); } } async fn async_func() { println!("async_func was cover...
} } }
{ break val; }
conditional_block
async2.rs
// compile-flags: --edition=2018 use core::{ future::Future, marker::Send, pin::Pin, }; fn non_async_func() { println!("non_async_func was covered"); let b = true; if b { println!("non_async_func println in block"); } } async fn async_func() { println!("async_func was cover...
}
{ let mut future = unsafe { Pin::new_unchecked(&mut future) }; use std::hint::unreachable_unchecked; static VTABLE: RawWakerVTable = RawWakerVTable::new( |_| unsafe { unreachable_unchecked() }, // clone |_| unsafe { unreachable_unchecked() }, // wake |_| unsaf...
identifier_body
ex2.rs
// Each new term in the Fibonacci sequence is generated by // adding the previous two terms. // By starting with 1 and 2, the first 10 terms will be: // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,... // By considering the terms in the Fibonacci sequence whose values // do not exceed four million, find the sum of the even-valued...
() { assert!(fibonacci(1) == 1); assert!(fibonacci(2) == 2); assert!(fibonacci(3) == 3); assert!(fibonacci(10) == 89); } #[test] fn test_fibonacci_list() { assert!(fibonacci_list(1) == [1]); assert!(fibonacci_list(2) == [1, 2]); assert!(fibonacci_list(3) == [1, 2, 3]); assert!(fibonacci...
test_fibonacci
identifier_name
ex2.rs
// Each new term in the Fibonacci sequence is generated by // adding the previous two terms. // By starting with 1 and 2, the first 10 terms will be: // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,... // By considering the terms in the Fibonacci sequence whose values // do not exceed four million, find the sum of the even-valued...
fn fibonacci(n: isize) -> isize { match n { 1 => 1, 2 => 2, x => fibonacci(x - 1) + fibonacci(x - 2) } } fn fibonacci_list(n: isize) -> Vec<isize> { (1..n+1).map(|x| fibonacci(x)).collect() } #[test] fn test_fibonacci() { assert!(fibonacci(1) == 1); assert!(fibonacci(2) =...
{ let mut n = 3; while fibonacci(n) < 4000000 { n += 1; } println!("{:?}", fibonacci_list(n - 1).iter().filter(|&i| i % 2 == 0).fold(0, |acc, x| acc + x)); }
identifier_body
ex2.rs
// Each new term in the Fibonacci sequence is generated by // adding the previous two terms. // By starting with 1 and 2, the first 10 terms will be: // 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,... // By considering the terms in the Fibonacci sequence whose values // do not exceed four million, find the sum of the even-valued...
} } fn fibonacci_list(n: isize) -> Vec<isize> { (1..n+1).map(|x| fibonacci(x)).collect() } #[test] fn test_fibonacci() { assert!(fibonacci(1) == 1); assert!(fibonacci(2) == 2); assert!(fibonacci(3) == 3); assert!(fibonacci(10) == 89); } #[test] fn test_fibonacci_list() { assert!(fibonacci...
1 => 1, 2 => 2, x => fibonacci(x - 1) + fibonacci(x - 2)
random_line_split
gdb-pretty-struct-and-enums.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
let empty_struct = EmptyStruct; let c_style_enum1 = CStyleEnum::CStyleEnumVar1; let c_style_enum2 = CStyleEnum::CStyleEnumVar2; let c_style_enum3 = CStyleEnum::CStyleEnumVar3; zzz(); // #break } fn zzz() { () }
random_line_split
gdb-pretty-struct-and-enums.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ the_first_field: isize, the_second_field: f64, the_third_field: bool, } struct EmptyStruct; enum CStyleEnum { CStyleEnumVar1, CStyleEnumVar2, CStyleEnumVar3, } fn main() { let regular_struct = RegularStruct { the_first_field: 101, the_second_field: 102.5, the_t...
RegularStruct
identifier_name
main.rs
#[macro_use] extern crate lazy_static; extern crate itertools; extern crate regex; use itertools::Itertools; use regex::Regex; macro_rules! some { ($expression:expr) => (match $expression { Some(value) => value, None => return None, }) } fn most_common(name: &str) -> String { name.chars()...
} let captures = match ROOM.captures(name) { Some(x) => x, _ => return None, }; let name = some!(captures.at(1)); let name = &name[..(name.len() - 1)]; let sector_id: usize = some!(captures.at(2).and_then(|x| x.parse().ok())); let checksum = some!(captures.at(3)); let...
fn parse_room(name: &str) -> Option<Room> { lazy_static! { static ref ROOM: Regex = Regex::new(r"((?:[a-z]+-)+)(\d+)\[([a-z]+)\]") .unwrap();
random_line_split
main.rs
#[macro_use] extern crate lazy_static; extern crate itertools; extern crate regex; use itertools::Itertools; use regex::Regex; macro_rules! some { ($expression:expr) => (match $expression { Some(value) => value, None => return None, }) } fn most_common(name: &str) -> String { name.chars(...
fn solve_two(rooms: &[Room]) -> Option<usize> { const BASE: u8 = b'a'; for room in rooms.iter().filter(|r| r.is_valid) { let key = (room.sector_id % 26) as u8; let decrypted = room.name .chars() .map(|c| match c { '-' =>'', _ => ((c as u8 ...
{ rooms.iter().filter(|r| r.is_valid).fold(0, |acc, r| acc + r.sector_id) }
identifier_body
main.rs
#[macro_use] extern crate lazy_static; extern crate itertools; extern crate regex; use itertools::Itertools; use regex::Regex; macro_rules! some { ($expression:expr) => (match $expression { Some(value) => value, None => return None, }) } fn most_common(name: &str) -> String { name.chars(...
} None } fn main() { let rooms: Vec<_> = include_str!("../input") .trim() .lines() .filter_map(|r| parse_room(r)) .collect(); println!("[1] The sum of valid rooms is {}.", solve_one(&rooms)); match solve_two(&rooms) { Some(id) => println!("[2] The objects are...
{ return Some(room.sector_id); }
conditional_block
main.rs
#[macro_use] extern crate lazy_static; extern crate itertools; extern crate regex; use itertools::Itertools; use regex::Regex; macro_rules! some { ($expression:expr) => (match $expression { Some(value) => value, None => return None, }) } fn most_common(name: &str) -> String { name.chars(...
(rooms: &[Room]) -> usize { rooms.iter().filter(|r| r.is_valid).fold(0, |acc, r| acc + r.sector_id) } fn solve_two(rooms: &[Room]) -> Option<usize> { const BASE: u8 = b'a'; for room in rooms.iter().filter(|r| r.is_valid) { let key = (room.sector_id % 26) as u8; let decrypted = room.name ...
solve_one
identifier_name
fixture_dao_testing.rs
extern crate proton_cli; use proton_cli::dao::FixtureDao; use proton_cli::error::Error; use proton_cli::project_types::Fixture; /// Implementation of FixtureDao for testing purposes. Uses given functions to return values. /// Functions are boxed so their sizes are known (pointers). /// The general naming convention ...
(&self, fixid: u32) -> Result<bool, Error> { (self.fixture_exists_fn)(fixid) } }
fixture_exists
identifier_name
fixture_dao_testing.rs
extern crate proton_cli; use proton_cli::dao::FixtureDao; use proton_cli::error::Error; use proton_cli::project_types::Fixture; /// Implementation of FixtureDao for testing purposes. Uses given functions to return values. /// Functions are boxed so their sizes are known (pointers). /// The general naming convention ...
fn get_num_channels(&self, fixid: u32) -> Result<u32, Error> { (self.get_num_channels_fn)(fixid) } fn fixture_exists(&self, fixid: u32) -> Result<bool, Error> { (self.fixture_exists_fn)(fixid) } }
random_line_split
crs.rs
use std::{ collections::HashSet, iter::FromIterator, path::Path, }; use serde::{ Deserialize, Serialize, }; use anyhow::Result; use rnc_core::grouper; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Crs { pub id: usize, crs_id: String, } #[derive(Clone, Debug, P...
() -> Self { Self { crs_id: HashSet::new(), } } } impl FromIterator<Crs> for CrsVec { fn from_iter<I: IntoIterator<Item = Crs>>(iter: I) -> Self { let mut c = CrsVec::default(); for i in iter { c.crs_id.insert(i.crs_id); } c } } imp...
default
identifier_name
crs.rs
use std::{ collections::HashSet, iter::FromIterator, path::Path, };
Deserialize, Serialize, }; use anyhow::Result; use rnc_core::grouper; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Crs { pub id: usize, crs_id: String, } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct CrsVec { crs_id: HashSet<String>, } imp...
use serde::{
random_line_split
crs.rs
use std::{ collections::HashSet, iter::FromIterator, path::Path, }; use serde::{ Deserialize, Serialize, }; use anyhow::Result; use rnc_core::grouper; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct Crs { pub id: usize, crs_id: String, } #[derive(Clone, Debug, P...
{ grouper::group::<Crs>(grouper::Criteria::AnyNumber, &path, 1, max, &output) }
identifier_body
test_cat.rs
//! The `cat` subtest. use std::borrow::Cow; use cretonne::ir::Function; use cton_reader::TestCommand; use subtest::{self, SubTest, Context, Result as STResult}; /// Object implementing the `test cat` sub-test. /// /// This command is used for testing the parser and function printer. It simply parses a function /// a...
else { Ok(Box::new(TestCat)) } } impl SubTest for TestCat { fn name(&self) -> Cow<str> { Cow::from("cat") } fn needs_verifier(&self) -> bool { false } fn run(&self, func: Cow<Function>, context: &Context) -> STResult<()> { subtest::run_filecheck(&func.display(...
{ Err(format!("No options allowed on {}", parsed)) }
conditional_block
test_cat.rs
//! The `cat` subtest. use std::borrow::Cow; use cretonne::ir::Function; use cton_reader::TestCommand; use subtest::{self, SubTest, Context, Result as STResult}; /// Object implementing the `test cat` sub-test. /// /// This command is used for testing the parser and function printer. It simply parses a function /// a...
} }
random_line_split
test_cat.rs
//! The `cat` subtest. use std::borrow::Cow; use cretonne::ir::Function; use cton_reader::TestCommand; use subtest::{self, SubTest, Context, Result as STResult}; /// Object implementing the `test cat` sub-test. /// /// This command is used for testing the parser and function printer. It simply parses a function /// a...
(&self, func: Cow<Function>, context: &Context) -> STResult<()> { subtest::run_filecheck(&func.display(context.isa).to_string(), context) } }
run
identifier_name
test_cat.rs
//! The `cat` subtest. use std::borrow::Cow; use cretonne::ir::Function; use cton_reader::TestCommand; use subtest::{self, SubTest, Context, Result as STResult}; /// Object implementing the `test cat` sub-test. /// /// This command is used for testing the parser and function printer. It simply parses a function /// a...
impl SubTest for TestCat { fn name(&self) -> Cow<str> { Cow::from("cat") } fn needs_verifier(&self) -> bool { false } fn run(&self, func: Cow<Function>, context: &Context) -> STResult<()> { subtest::run_filecheck(&func.display(context.isa).to_string(), context) } }
{ assert_eq!(parsed.command, "cat"); if !parsed.options.is_empty() { Err(format!("No options allowed on {}", parsed)) } else { Ok(Box::new(TestCat)) } }
identifier_body
extern-stress.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 ...
(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1u { data } else { task::yield(); count(data - 1u) + count(data - 1u) } } fn count(n: uint) -> uint { unsafe { rustrt::rust_dbg_call(cb, n) } } pub fn main() { for iter::repeat(100u) { do task::spaw...
cb
identifier_name
extern-stress.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 ...
{ for iter::repeat(100u) { do task::spawn { assert!(count(5u) == 16u); }; } }
identifier_body
extern-stress.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 ...
unsafe { rustrt::rust_dbg_call(cb, n) } } pub fn main() { for iter::repeat(100u) { do task::spawn { assert!(count(5u) == 16u); }; } }
fn count(n: uint) -> uint {
random_line_split
extern-stress.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 ...
else { task::yield(); count(data - 1u) + count(data - 1u) } } fn count(n: uint) -> uint { unsafe { rustrt::rust_dbg_call(cb, n) } } pub fn main() { for iter::repeat(100u) { do task::spawn { assert!(count(5u) == 16u); }; } }
{ data }
conditional_block
mod.rs
use super::managed_display::ManagedDisplay; use entities::{ EntitiesState, EntitiesHelper, EntityID, ComponentID, NativeComponentType }; use nalgebra::na; use nalgebra::na::{ Vec3, Eye }; use std::collections::{ HashSet, HashMap }; use std::sync::Arc; use super::sprite_displayer::SpriteDisplayer; use super::Drawable; u...
for (cmp, &(ref sprite, _)) in self.sprites.iter() { let pos = physics::get_entity_position(state, &state.get_owner(cmp).unwrap()); let translationMatrix = na::Mat4::new( 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0...
log(log::LogRecord::new(log::Warning, format!("No active camera on the scene"))); Eye::new_identity(4) });
random_line_split
mod.rs
use super::managed_display::ManagedDisplay; use entities::{ EntitiesState, EntitiesHelper, EntityID, ComponentID, NativeComponentType }; use nalgebra::na; use nalgebra::na::{ Vec3, Eye }; use std::collections::{ HashSet, HashMap }; use std::sync::Arc; use super::sprite_displayer::SpriteDisplayer; use super::Drawable; u...
(&mut self, state: &EntitiesState, log: |log::LogRecord|) { // getting the list of all sprite displayer components let listOfComponents = state .get_visible_native_components("spriteDisplay").move_iter() .collect::<HashSet<ComponentID>>(); // removing from the list the...
update_sprite_displayers
identifier_name
mod.rs
use super::managed_display::ManagedDisplay; use entities::{ EntitiesState, EntitiesHelper, EntityID, ComponentID, NativeComponentType }; use nalgebra::na; use nalgebra::na::{ Vec3, Eye }; use std::collections::{ HashSet, HashMap }; use std::sync::Arc; use super::sprite_displayer::SpriteDisplayer; use super::Drawable; u...
self.customDisplay.draw(state, |l| log(l)); } fn update_sprite_displayers(&mut self, state: &EntitiesState, log: |log::LogRecord|) { // getting the list of all sprite displayer components let listOfComponents = state .get_visible_native_components("spriteDisplay").move_i...
{ self.update_sprite_displayers(state, |l| log(l)); let camera = DisplaySystem::get_camera(state).unwrap_or_else(|| { log(log::LogRecord::new(log::Warning, format!("No active camera on the scene"))); Eye::new_identity(4) }); for (cmp, &(ref sprite, _)) in self.s...
identifier_body
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The implementation of the DOM. //! //! The DOM is comprised of interfaces (defined by specifications using //!...
pub mod dompointreadonly; pub mod domquad; pub mod domrect; pub mod domrectreadonly; pub mod domstringmap; pub mod domtokenlist; pub mod element; pub mod errorevent; pub mod event; pub mod eventsource; pub mod eventtarget; pub mod extendableevent; pub mod extendablemessageevent; pub mod file; pub mod filelist; pub mod ...
random_line_split
cast-in-array-size.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 _a: [bool; 1 as usize]; let _b: [isize; SIZE as usize] = [1; SIZE as usize]; let _c: [bool; '\n' as usize] = [true; '\n' as usize]; let _d: [bool; true as usize] = [true; true as usize]; }
identifier_body
cast-in-array-size.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 _a: [bool; 1 as usize]; let _b: [isize; SIZE as usize] = [1; SIZE as usize]; let _c: [bool; '\n' as usize] = [true; '\n' as usize]; let _d: [bool; true as usize] = [true; true as usize]; }
main
identifier_name
cast-in-array-size.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass //...
// http://rust-lang.org/COPYRIGHT.
random_line_split
issue-4446.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 (tx, rx) = channel(); tx.send("hello, world").unwrap(); thread::spawn(move|| { println(rx.recv().unwrap()); }).join().ok().unwrap(); }
identifier_body
issue-4446.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 ...
use std::sync::mpsc::channel; use std::thread; pub fn main() { let (tx, rx) = channel(); tx.send("hello, world").unwrap(); thread::spawn(move|| { println(rx.recv().unwrap()); }).join().ok().unwrap(); }
#![feature(old_io)] use std::old_io::println;
random_line_split
issue-4446.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 (tx, rx) = channel(); tx.send("hello, world").unwrap(); thread::spawn(move|| { println(rx.recv().unwrap()); }).join().ok().unwrap(); }
main
identifier_name
68.rs
/* Problem 68: Magic 5-gon ring * * Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each line adding to nine. * * Working clockwise, and starting from the group of three with the numerically lowest external node (4,3,2 in this example), * each solution can be described uniquely. For ...
(numbers: &[u8]) -> Option<Solution> { let (external, others) = numbers.split_at(RING_WIDTH); if external.iter().min()!= external.first() { return None; } let mut sets: Solution = external .iter() .map(|&e| { let mut v = SolutionPart::new(); v.push(e); ...
maybe_solution
identifier_name
68.rs
/* Problem 68: Magic 5-gon ring * * Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each line adding to nine. * * Working clockwise, and starting from the group of three with the numerically lowest external node (4,3,2 in this example), * each solution can be described uniquely. For ...
if external.iter().min()!= external.first() { return None; } let mut sets: Solution = external .iter() .map(|&e| { let mut v = SolutionPart::new(); v.push(e); v }) .collect(); for n in 1..LINE_LENGTH { for (set_index, se...
.filter_map(|opt| opt) } fn maybe_solution(numbers: &[u8]) -> Option<Solution> { let (external, others) = numbers.split_at(RING_WIDTH);
random_line_split
68.rs
/* Problem 68: Magic 5-gon ring * * Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each line adding to nine. * * Working clockwise, and starting from the group of three with the numerically lowest external node (4,3,2 in this example), * each solution can be described uniquely. For ...
type SolutionPart = SmallVec<[u8; LINE_LENGTH]>; type Solution = SmallVec<[SolutionPart; RING_WIDTH]>; fn solutions() -> impl Iterator<Item = Solution> { let digits: SmallVec<[u8; MAX_NUMBER as usize + 1]> = (1..=MAX_NUMBER).collect(); itertools::unfold(digits.permutations(), |state| { state.permute...
{ let mut len = 0; for set in solution { for num in set { if *num < 10 { len += 1 } else { len += 2; } } } len <= MAX_SOLUTION_LENGTH }
identifier_body
68.rs
/* Problem 68: Magic 5-gon ring * * Consider the following "magic" 3-gon ring, filled with the numbers 1 to 6, and each line adding to nine. * * Working clockwise, and starting from the group of three with the numerically lowest external node (4,3,2 in this example), * each solution can be described uniquely. For ...
} } true }
{}
conditional_block
06.rs
/* Problem 6: Sum square difference * * The sum of the squares of the first ten natural numbers is, * 1² + 2² +... + 10² = 385 * * The square of the sum of the first ten natural numbers is, * (1 + 2 +... + 10)² = 55² = 3025 * * Hence the difference between the sum of the squares of the first ten natural numbers...
first_natural_numbers: Vec<u32> = (1..101).collect(); let terms = combinations::new(first_natural_numbers) .filter(|&(a, b)| a!= b) // No 2 * a * a .filter(|&(a, b)| a < b) // No 2 * a * b + 2 * b * a .map(|(a, b)| 2 * a * b); let result = terms.fold(0, |result, term| result + term); ...
let
identifier_name
06.rs
/* Problem 6: Sum square difference * * The sum of the squares of the first ten natural numbers is, * 1² + 2² +... + 10² = 385 * * The square of the sum of the first ten natural numbers is, * (1 + 2 +... + 10)² = 55² = 3025 * * Hence the difference between the sum of the squares of the first ten natural numbers...
st_natural_numbers: Vec<u32> = (1..101).collect(); let terms = combinations::new(first_natural_numbers) .filter(|&(a, b)| a != b) // No 2 * a * a .filter(|&(a, b)| a < b) // No 2 * a * b + 2 * b * a .map(|(a, b)| 2 * a * b); let result = terms.fold(0, |result, term| result + term); ...
identifier_body
06.rs
/* Problem 6: Sum square difference * * The sum of the squares of the first ten natural numbers is, * 1² + 2² +... + 10² = 385 * * The square of the sum of the first ten natural numbers is, * (1 + 2 +... + 10)² = 55² = 3025 * * Hence the difference between the sum of the squares of the first ten natural numbers...
* Find the difference between the sum of the squares of the first one hundred natural numbers and * the square of the sum. */ use shared::combinations; // (a + b + c +...)² = a² + b² + c² +... + 2ab + 2ac + 2ad + 2bc... // (a + b + c +...)² - (a² + b² + c² +...) = 2ab + 2ac + 2ad + 2bc... fn main() { let first_...
*
random_line_split
local_follow.rs
use std::path::Path; use anyhow::{bail, Result}; use pueue_lib::network::protocol::GenericStream; use crate::commands::get_state; use crate::display::follow_local_task_logs; pub async fn local_follow( stream: &mut GenericStream, pueue_directory: &Path, task_id: &Option<usize>, lines: Option<usize>, ...
let running_ids = running_ids .iter() .map(|id| id.to_string()) .collect::<Vec<_>>() .join(", "); bail!( "Multiple tasks are running, please select one of the follo...
{ // The user can specify the id of the task they want to follow // If the id isn't specified and there's only a single running task, this task will be used. // However, if there are multiple running tasks, the user will have to specify an id. let task_id = match task_id { Some(task_id) => *task...
identifier_body
local_follow.rs
use std::path::Path; use anyhow::{bail, Result}; use pueue_lib::network::protocol::GenericStream; use crate::commands::get_state; use crate::display::follow_local_task_logs; pub async fn local_follow( stream: &mut GenericStream, pueue_directory: &Path, task_id: &Option<usize>, lines: Option<usize>, ...
Ok(()) }
follow_local_task_logs(pueue_directory, task_id, lines);
random_line_split
local_follow.rs
use std::path::Path; use anyhow::{bail, Result}; use pueue_lib::network::protocol::GenericStream; use crate::commands::get_state; use crate::display::follow_local_task_logs; pub async fn
( stream: &mut GenericStream, pueue_directory: &Path, task_id: &Option<usize>, lines: Option<usize>, ) -> Result<()> { // The user can specify the id of the task they want to follow // If the id isn't specified and there's only a single running task, this task will be used. // However, if th...
local_follow
identifier_name
local_follow.rs
use std::path::Path; use anyhow::{bail, Result}; use pueue_lib::network::protocol::GenericStream; use crate::commands::get_state; use crate::display::follow_local_task_logs; pub async fn local_follow( stream: &mut GenericStream, pueue_directory: &Path, task_id: &Option<usize>, lines: Option<usize>, ...
1 => running_ids[0], _ => { let running_ids = running_ids .iter() .map(|id| id.to_string()) .collect::<Vec<_>>() .join(", "); bail!( ...
{ bail!("There are no running tasks."); }
conditional_block
user.rs
use hyper::header::Cookie; use jwt::{encode, decode, Header, Validation}; use config::Config; use controller::context::{RequestContext, ResponseContext}; use model::entity::User; pub fn user_session<F>(mut request: RequestContext, seed: F) -> ResponseContext where F: Fn(RequestContext) -> ResponseContext { if...
let key = Config::idem().security.cookie_key.as_ref(); let token = encode(&header, response.user.as_ref().unwrap(), key).unwrap_or("".to_string()); if!token.is_empty() { response.set_cookie(format!("jwt={}; Path=/;", token)); } } response }
if response.clean_user { response.set_cookie("jwt=deleted; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT".to_string()); } else if response.user.is_some() { let header = Header::default();
random_line_split
user.rs
use hyper::header::Cookie; use jwt::{encode, decode, Header, Validation}; use config::Config; use controller::context::{RequestContext, ResponseContext}; use model::entity::User; pub fn
<F>(mut request: RequestContext, seed: F) -> ResponseContext where F: Fn(RequestContext) -> ResponseContext { if let Some(ref cookie) = request.headers.get::<Cookie>() { let token = cookie.get("jwt").unwrap_or(""); if!token.is_empty() { let key = Config::idem().security.cookie_key.as...
user_session
identifier_name
user.rs
use hyper::header::Cookie; use jwt::{encode, decode, Header, Validation}; use config::Config; use controller::context::{RequestContext, ResponseContext}; use model::entity::User; pub fn user_session<F>(mut request: RequestContext, seed: F) -> ResponseContext where F: Fn(RequestContext) -> ResponseContext { if...
} response }
{ response.set_cookie(format!("jwt={}; Path=/;", token)); }
conditional_block
user.rs
use hyper::header::Cookie; use jwt::{encode, decode, Header, Validation}; use config::Config; use controller::context::{RequestContext, ResponseContext}; use model::entity::User; pub fn user_session<F>(mut request: RequestContext, seed: F) -> ResponseContext where F: Fn(RequestContext) -> ResponseContext
let header = Header::default(); let key = Config::idem().security.cookie_key.as_ref(); let token = encode(&header, response.user.as_ref().unwrap(), key).unwrap_or("".to_string()); if!token.is_empty() { response.set_cookie(format!("jwt={}; Path=/;", token)); } } ...
{ if let Some(ref cookie) = request.headers.get::<Cookie>() { let token = cookie.get("jwt").unwrap_or(""); if !token.is_empty() { let key = Config::idem().security.cookie_key.as_ref(); match decode::<User>(token, key, &Validation::default()) { Ok(token_data) ...
identifier_body
fmt.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Marker types fo...
(&mut self) -> Option<(usize, char)> { self.inner.next().map(|(i, &b)| unsafe { (i, from_u32_unchecked(b as u32)) }) } } impl<'a> SingleByteCharIndices<'a> { #[inline] pub fn new(buf: &'a [u8]) -> SingleByteCharIndices<'a> { SingleByte...
next
identifier_name
fmt.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Marker types fo...
} #[inline(always)] unsafe fn from_u32_unchecked(n: u32) -> char { mem::transmute(n) } pub struct SingleByteCharIndices<'a> { inner: iter::Enumerate<slice::Iter<'a, u8>>, } impl<'a> Iterator for SingleByteCharIndices<'a> { type Item = (usize, char); #[inl...
{ Fixup { drop_left: 0, drop_right: 0, insert_len: 0, insert_bytes: [0; 4], } }
identifier_body
fmt.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Marker types fo...
unsafe fn fixup(lhs: &[u8], rhs: &[u8]) -> imp::Fixup { const ERR: &'static str = "WTF8: internal error"; if lhs.len() >= 3 && rhs.len() >= 3 { if let (Some(Codepoint { meaning: Meaning::LeadSurrogate(hi),.. }), Some(Codepoint { meaning: Meaning::TrailSurrogate(lo),....
random_line_split
macro-input-future-proofing.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 ...
() { }
main
identifier_name
macro-input-future-proofing.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ }
identifier_body
macro-input-future-proofing.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 ...
($pa:pat, ) => (); ($pa:pat $pb:pat $ty:ty,) => (); //~^ ERROR `$pa:pat` is followed by `$pb:pat`, which is not allowed //~^^ ERROR `$pb:pat` is followed by `$ty:ty`, which is not allowed ($($ty:ty)* -) => (); //~ ERROR `$ty:ty` is followed by `-` ($($a:ty, $b:ty)* -) => (); //~ ERROR `$b:ty` is...
($pa:pat >) => (); //~ ERROR `$pa:pat` is followed by `>`, which is not allowed for `pat`
random_line_split
generator.rs
use super::super::P; use super::*; use rand::Rng; pub fn generate<R: Rng>(size: i32, n_alpha: i32, rng: &mut R) -> Option<Problem> { let mut current_problem = Problem::new(size, n_alpha); let mut prev_score = (size * size * (n_alpha + 1)) as f64; let max_step = size * size * 20; let temperature = 6.0...
{ let mut n_clues = 0; for &loc in &[ClueLoc::Top, ClueLoc::Bottom, ClueLoc::Left, ClueLoc::Right] { for i in 0..problem.size() { if problem.get_clue(loc, i) != NO_CLUE { n_clues += 1; } } } n_clues }
identifier_body
generator.rs
use super::super::P; use super::*; use rand::Rng; pub fn
<R: Rng>(size: i32, n_alpha: i32, rng: &mut R) -> Option<Problem> { let mut current_problem = Problem::new(size, n_alpha); let mut prev_score = (size * size * (n_alpha + 1)) as f64; let max_step = size * size * 20; let temperature = 6.0; for _ in 0..max_step { let mut update_cand = vec![];...
generate
identifier_name
generator.rs
use super::super::P; use super::*; use rand::Rng; pub fn generate<R: Rng>(size: i32, n_alpha: i32, rng: &mut R) -> Option<Problem> { let mut current_problem = Problem::new(size, n_alpha); let mut prev_score = (size * size * (n_alpha + 1)) as f64; let max_step = size * size * 20; let temperature = 6.0...
if keep_update { if field.is_solved() { let mut field = Field::from_problem(&current_problem); let mut isok = true; field.apply_methods(); for y in 0..size { for x in 0..size { ...
{ current_score = compute_score(&current_problem, &field); keep_update = prev_score > current_score || rng.gen::<f64>() < ((prev_score - current_score) / temperature).exp(); }
conditional_block
generator.rs
use super::super::P; use super::*; use rand::Rng; pub fn generate<R: Rng>(size: i32, n_alpha: i32, rng: &mut R) -> Option<Problem> { let mut current_problem = Problem::new(size, n_alpha); let mut prev_score = (size * size * (n_alpha + 1)) as f64; let max_step = size * size * 20; let temperature = 6.0...
} if keep_update { if field.is_solved() { let mut field = Field::from_problem(&current_problem); let mut isok = true; field.apply_methods(); for y in 0..size { for x in 0..siz...
current_score = compute_score(&current_problem, &field); keep_update = prev_score > current_score || rng.gen::<f64>() < ((prev_score - current_score) / temperature).exp();
random_line_split
shared.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <bgamari@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2...
unsafe { &*self.ptr.value.get() } } } impl<'a, T> DerefMut for SharedRef<'a, T> { fn deref_mut<'b>(&'b mut self) -> &'b mut T { unsafe { &mut *self.ptr.value.get() } } } unsafe impl<T: Send> Sync for Shared<T> {}
impl<'a, T> Deref for SharedRef<'a, T> { type Target = T; fn deref<'b>(&'b self) -> &'b T {
random_line_split
shared.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <bgamari@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2...
/// Borrow a reference to the value pub fn borrow<'a>(&'a self, crit: &'a NoInterrupts) -> SharedRef<'a, T> { SharedRef {ptr: self, crit: crit} } } impl<'a, T> Deref for SharedRef<'a, T> { type Target = T; fn deref<'b>(&'b self) -> &'b T { unsafe { &*self.ptr.value.get() } } } impl<'a,...
{ Shared { value: UnsafeCell::new(value), } }
identifier_body
shared.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Ben Gamari <bgamari@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2...
<T> { pub value: UnsafeCell<T>, } /// A reference to a shared value pub struct SharedRef<'a, T: 'a> { ptr: &'a Shared<T>, #[allow(dead_code)] crit: &'a NoInterrupts } impl<T> Shared<T> { /// Create a new `Shared` value pub fn new(value: T) -> Shared<T> { Shared { value: UnsafeCell::new(value), ...
Shared
identifier_name
server.rs
/* This example creates a D-Bus server with the following functionality: It registers the "com.example.dbustest" name, creates a "/hello" object path, which has an "com.example.dbustest" interface. The interface has a "Hello" method (which takes no arguments and returns a string), and a "HelloHappened" sig...
//...and a method inside the interface. f.method("Hello", (), move |m| { // This is the callback that will be called when another peer on the bus calls our method. // the callback receives "MethodInfo" struct and can return either an error, or a list of ...
{ // Let's start by starting up a connection to the session bus and register a name. let c = Connection::get_private(BusType::Session).unwrap(); c.register_name("com.example.dbustest", NameFlag::ReplaceExisting as u32).unwrap(); // The choice of factory tells us what type of tree we want, // and if...
identifier_body
server.rs
/* This example creates a D-Bus server with the following functionality: It registers the "com.example.dbustest" name, creates a "/hello" object path, which has an "com.example.dbustest" interface. The interface has a "Hello" method (which takes no arguments and returns a string), and a "HelloHappened" sig...
// messages to send back. let name: &str = m.msg.read1()?; let s = format!("Hello {}!", name); let mret = m.msg.method_return().append1(s); let sig = signal.msg(m.path.get_name(), m.iface.get_name()) .append1(&*name); ...
random_line_split
server.rs
/* This example creates a D-Bus server with the following functionality: It registers the "com.example.dbustest" name, creates a "/hello" object path, which has an "com.example.dbustest" interface. The interface has a "Hello" method (which takes no arguments and returns a string), and a "HelloHappened" sig...
() { // Let's start by starting up a connection to the session bus and register a name. let c = Connection::get_private(BusType::Session).unwrap(); c.register_name("com.example.dbustest", NameFlag::ReplaceExisting as u32).unwrap(); // The choice of factory tells us what type of tree we want, // and...
main
identifier_name
borrowck-borrow-from-expr-block.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 ...
pub fn main() { test1(box(GC) box 22); }
{ borrow(&*(*x).clone(), |p| { let x_a = &**x as *const int; assert!((x_a as uint) != (p as *const int as uint)); assert_eq!(unsafe{*x_a}, *p); }) }
identifier_body
borrowck-borrow-from-expr-block.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.
// except according to those terms. use std::gc::{Gc, GC}; fn borrow(x: &int, f: |x: &int|) { f(x) } fn test1(x: Gc<Box<int>>) { borrow(&*(*x).clone(), |p| { let x_a = &**x as *const int; assert!((x_a as uint)!= (p as *const int as uint)); assert_eq!(unsafe{*x_a}, *p); }) } pub ...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
borrowck-borrow-from-expr-block.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(x: &int, f: |x: &int|) { f(x) } fn test1(x: Gc<Box<int>>) { borrow(&*(*x).clone(), |p| { let x_a = &**x as *const int; assert!((x_a as uint)!= (p as *const int as uint)); assert_eq!(unsafe{*x_a}, *p); }) } pub fn main() { test1(box(GC) box 22); }
borrow
identifier_name
definitions.rs
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
fn visit_body(&mut self, body: &'tcx rustc_hir::Body) { let fn_id = self.tcx.hir().body_owner_def_id(body.id()); if self.tcx.item_name(fn_id.to_def_id()) == self.rerast_types_symbol { let tables = self.tcx.typeck_tables_of(fn_id); let mut types = body.params.iter().map(|arg| ...
}
random_line_split
definitions.rs
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
replace_symbol: Symbol::intern("Replace"), }) } } }
{ let tables = self.tcx.typeck_tables_of(fn_id); let mut types = body.params.iter().map(|arg| tables.node_type(arg.hir_id)); self.definitions = Some(RerastDefinitions { statements: types .next() .expect("Internal error - missing...
conditional_block
definitions.rs
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
(&mut self, body: &'tcx rustc_hir::Body) { let fn_id = self.tcx.hir().body_owner_def_id(body.id()); if self.tcx.item_name(fn_id.to_def_id()) == self.rerast_types_symbol { let tables = self.tcx.typeck_tables_of(fn_id); let mut types = body.params.iter().map(|arg| tables.node_type(...
visit_body
identifier_name
diagnostic.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program 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...
{ Error, } pub trait DiagnosableError { fn message(&self) -> String; fn suggestion(&self) -> Option<String>; } #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct Diagnostic { pub level: Level, pub message: String, pub spans: Vec<Span>, pub suggestion: Option<String>, } impl D...
Level
identifier_name
diagnostic.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program 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...
write!(f, ": {}.", &self.message)?; if let Some(suggestion) = &self.suggestion { write!(f, "\n{}", suggestion)?; } write!(f, "\n") } }
random_line_split
diagnostic.rs
// Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation // Copyright (C) 2020 Stacks Open Internet Foundation // // This program 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...
else if self.spans.len() > 1 { let lines: Vec<String> = self .spans .iter() .map(|s| format!("line: {}", s.start_line)) .collect(); write!(f, " ({})", lines.join(", "))?; } write!(f, ": {}.", &self.message)?; if...
{ write!( f, " (line {}, column {})", self.spans[0].start_line, self.spans[0].start_column )?; }
conditional_block
mod.rs
// The MIT License (MIT) // // Copyright (c) 2016-2022 Ivan Dejanovic // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to ...
// The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PU...
// copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: //
random_line_split
mod.rs
// The MIT License (MIT) // // Copyright (c) 2016-2022 Ivan Dejanovic // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to ...
(mut codefile: File) -> Vec<String> { let mut code: String = String::new(); let result = codefile.read_to_string(&mut code); match result { Ok(_) => compile(code), Err(e) => panic!("Error reading souce file: {}", e), } } fn compile(code: String) -> Vec<String> { println!("{}", code...
cpl
identifier_name
mod.rs
// The MIT License (MIT) // // Copyright (c) 2016-2022 Ivan Dejanovic // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to ...
fn compile(code: String) -> Vec<String> { println!("{}", code); Vec::new() }
{ let mut code: String = String::new(); let result = codefile.read_to_string(&mut code); match result { Ok(_) => compile(code), Err(e) => panic!("Error reading souce file: {}", e), } }
identifier_body
path.rs
use std::fmt::{self, Debug, Formatter}; use std::fs; use std::path::{Path, PathBuf}; use filetime::FileTime; use git2; use glob::Pattern; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use ops; use util::{self, CargoError, CargoResult, internal}; use util::Config; pub struct PathSou...
#[cfg(windows)] fn join(path: &Path, data: &[u8]) -> CargoResult<PathBuf> { use std::str; match str::from_utf8(data) { Ok(s) => Ok(path.join(s)), Err(..) => Err(internal("cannot process path in git with a non \ ...
{ use std::os::unix::prelude::*; use std::ffi::OsStr; Ok(path.join(<OsStr as OsStrExt>::from_bytes(data))) }
identifier_body
path.rs
use std::fmt::{self, Debug, Formatter}; use std::fs; use std::path::{Path, PathBuf}; use filetime::FileTime; use git2; use glob::Pattern; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use ops; use util::{self, CargoError, CargoResult, internal}; use util::Config; pub struct PathSou...
// Don't recurse into any sub-packages that we have if!is_root && fs::metadata(&path.join("Cargo.toml")).is_ok() { return Ok(()) } for dir in fs::read_dir(path)? { let dir = dir?.path(); let name = dir.file_name().and_then(|s| s.to_str()); ...
{ if (*filter)(path) { ret.push(path.to_path_buf()); } return Ok(()) }
conditional_block
path.rs
use std::fmt::{self, Debug, Formatter}; use std::fs; use std::path::{Path, PathBuf}; use filetime::FileTime; use git2; use glob::Pattern; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use ops; use util::{self, CargoError, CargoResult, internal}; use util::Config; pub struct PathSou...
(&self, pkg: &Package, repo: git2::Repository, filter: &mut FnMut(&Path) -> bool) -> CargoResult<Vec<PathBuf>> { warn!("list_files_git {}", pkg.package_id()); let index = repo.index()?; let root = repo.workdir().ok_or_else(|| { internal("Ca...
list_files_git
identifier_name
path.rs
use std::fmt::{self, Debug, Formatter}; use std::fs; use std::path::{Path, PathBuf}; use filetime::FileTime; use git2; use glob::Pattern; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use ops; use util::{self, CargoError, CargoResult, internal}; use util::Config; pub struct PathSou...
// don't cross submodule boundaries if cur.join(".git").is_dir() { break } match cur.parent() { Some(parent) => cur = parent, None => break, } } return None; } fn list_files_git(&self, pk...
} } }
random_line_split
issue-6157.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 ...
pub fn main() { let f = |x,y| muli(x,y); { let g = &f; let h = g as &OpInt; squarei(3, h); } }
{ x * y }
identifier_body
issue-6157.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 squarei<'a>(x: int, op: &'a OpInt) -> int { op.call(x, x) } fn muli(x:int, y:int) -> int { x * y } pub fn main() { let f = |x,y| muli(x,y); { let g = &f; let h = g as &OpInt; squarei(3, h); } }
(*self)(a, b)
random_line_split
issue-6157.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 ...
(&self, a:int, b:int) -> int { (*self)(a, b) } } fn squarei<'a>(x: int, op: &'a OpInt) -> int { op.call(x, x) } fn muli(x:int, y:int) -> int { x * y } pub fn main() { let f = |x,y| muli(x,y); { let g = &f; let h = g as &OpInt; squarei(3, h); } }
call
identifier_name
angles.rs
use std::num::{ Float, cast }; use std::f64; pub use self::Angle::{Deg, Rad, Grad}; pub trait Trigonometry<T>: Sized { fn sin(self) -> T; fn cos(self) -> T; fn tan(self) -> T; } pub enum Angle<T> { Deg(T), Rad(T), Grad(T) } impl<T> Angle<T> { pub fn unwrap(self) -> T { ma...
pub fn to_grad(self) -> Self { Grad(match self { Rad(v) => v * cast(200.0 / f64::consts::PI).unwrap(), Deg(v) => v * cast(200.0 / 180.0).unwrap(), Grad(v) => v }) } } impl<T> Trigonometry<T> for Angle<T> where T: Float { fn sin(self) -> T { se...
{ Deg(match self { Rad(v) => v * cast(180.0 / f64::consts::PI).unwrap(), Deg(v) => v, Grad(v) => v * cast(180.0 / 200.0).unwrap() }) }
identifier_body
angles.rs
use std::num::{ Float, cast }; use std::f64; pub use self::Angle::{Deg, Rad, Grad}; pub trait Trigonometry<T>: Sized { fn sin(self) -> T; fn cos(self) -> T; fn tan(self) -> T; } pub enum Angle<T> { Deg(T), Rad(T), Grad(T) } impl<T> Angle<T> { pub fn unwrap(self) -> T { ma...
(self) -> T { self.to_rad().unwrap().tan() } } #[cfg(test)] mod tests { use super::*; use std::num::Float; use std::f64; #[test] fn to_radians() { assert_eq!(Deg(0.0).to_rad().unwrap(), Float::zero()); assert_eq!(Deg(180.0).to_rad().unwrap(), f64::consts::PI); } #[test...
tan
identifier_name
angles.rs
use std::num::{ Float, cast }; use std::f64; pub use self::Angle::{Deg, Rad, Grad}; pub trait Trigonometry<T>: Sized { fn sin(self) -> T; fn cos(self) -> T; fn tan(self) -> T; } pub enum Angle<T> { Deg(T), Rad(T), Grad(T) } impl<T> Angle<T> { pub fn unwrap(self) -> T { ma...
assert_eq!(Deg(180.0).to_rad().unwrap(), f64::consts::PI); } #[test] fn sin() { assert_eq!(Deg(0.0).sin(), Float::zero()); assert!(Deg(180.0).sin().abs() < f64::EPSILON); } }
use std::f64; #[test] fn to_radians() { assert_eq!(Deg(0.0).to_rad().unwrap(), Float::zero());
random_line_split
errors.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...
rdr.lines().enumerate().filter_map(|(line_no, ln)| { parse_expected(line_no + 1, ln.unwrap().as_slice(), re) }).collect() } fn parse_expected(line_num: uint, line: &str, re: &Regex) -> Option<ExpectedError> { re.captures(line).and_then(|caps| { let adjusts = caps.name("adjusts").len(); ...
let mut rdr = BufferedReader::new(File::open(testfile).unwrap());
random_line_split
errors.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...
{ pub line: uint, pub kind: String, pub msg: String, } pub static EXPECTED_PATTERN : &'static str = r"//~(?P<adjusts>\^*)\s*(?P<kind>\S*)\s*(?P<msg>.*)"; // Load any test directives embedded in the file pub fn load_errors(re: &Regex, testfile: &Path) -> Vec<ExpectedError> { let mut rdr = BufferedRead...
ExpectedError
identifier_name
recursion_limit_deref.rs
// Copyright 2017 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 deref(&self) -> &$inner { &self.0 } } } } struct Bottom; impl Bottom { fn new() -> Bottom { Bottom } } link!(Top, A); link!(A, B); link!(B, C); link!(C, D); link!(D, E); link!(E, F); link!(F, G); link!(G, H); link!(H, I); link!(I, J); link!(J, K);...
} impl std::ops::Deref for $outer { type Target = $inner;
random_line_split
recursion_limit_deref.rs
// Copyright 2017 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 ...
() -> Bottom { Bottom } } link!(Top, A); link!(A, B); link!(B, C); link!(C, D); link!(D, E); link!(E, F); link!(F, G); link!(G, H); link!(H, I); link!(I, J); link!(J, K); link!(K, Bottom); fn main() { let t = Top::new(); let x: &Bottom = &t; //~ ERROR mismatched types //~^ error recursion limi...
new
identifier_name