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 |
|---|---|---|---|---|
main.rs | //! This example uses the `glium` library, a high level, safe wrapper for OpenGL.
//!
//! It is based off the example in the [official tutorial].
//!
//! [official tutorial]: https://github.com/glium/glium/tree/master/book
use glium::glutin::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
... |
in vec2 a_color;
out vec4 color;
void main() {
color = vec4(a_color, 0.0, 1.0);
}
"#;
let program =
glium::Program::from_source(&display, vertex_shader_src, fragment_shader_src, None)
.unwrap();
let draw = move || {
let mut target = ... | "#;
let fragment_shader_src = r#"
#version 140 | random_line_split |
associated-types-bound.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// Test equality constrai32s on associated types in a where clause.
pub trait ToI32 {
fn to_i32(&self) -> i32;
}
impl ToI32 for i32 {
... | random_line_split | |
associated-types-bound.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 trait GetToI32
{
type R : ToI32;
fn get(&self) -> <Self as GetToI32>::R;
}
impl GetToI32 for i32 {
type R = i32;
fn get(&self) -> i32 { *self }
}
impl GetToI32 for u32 {
type R = u32;
fn get(&self) -> u32 { *self }
}
fn foo<G>(g: G) -> i32
where G : GetToI32
{
ToI32::to_i32(&... | { *self as i32 } | identifier_body |
associated-types-bound.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_eq!(foo(22i32), 22);
assert_eq!(foo(22u32), 22);
}
| main | identifier_name |
storage_live_dead_in_statics.rs | // Check that when we compile the static `XXX` into MIR, we do not
// generate `StorageStart` or `StorageEnd` statements.
// EMIT_MIR storage_live_dead_in_statics.XXX.mir_map.0.mir
static XXX: &'static Foo = &Foo {
tup: "hi",
data: &[
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, ... | {
println!("{:?}", XXX);
} | identifier_body | |
storage_live_dead_in_statics.rs | // Check that when we compile the static `XXX` into MIR, we do not
// generate `StorageStart` or `StorageEnd` statements.
// EMIT_MIR storage_live_dead_in_statics.XXX.mir_map.0.mir
static XXX: &'static Foo = &Foo {
tup: "hi",
data: &[
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, ... | () {
println!("{:?}", XXX);
}
| main | identifier_name |
storage_live_dead_in_statics.rs | // Check that when we compile the static `XXX` into MIR, we do not
// generate `StorageStart` or `StorageEnd` statements.
// EMIT_MIR storage_live_dead_in_statics.XXX.mir_map.0.mir
static XXX: &'static Foo = &Foo {
tup: "hi",
data: &[ | (0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
(0, 1), (0, 2), (0, 3),
... | random_line_split | |
main.rs | extern crate rustc_serialize;
use std::fs::File;
use std::io::prelude::*;
use rustc_serialize::hex::{FromHex, ToHex};
fn xor_hex_strings(str1: &str, str2: &str) -> Option<String> |
fn score_phrase(phrase: &str, score: &mut f64) {
for letter in phrase.to_lowercase().chars() {
match letter {
'a' => *score += 8.167,
'b' => *score += 1.492,
'c' => *score += 2.782,
'd' => *score += 4.253,
'e' => *score += 12.702,
'f'... | {
if str1.len() != str2.len() {
None
} else {
let bytes1 = str1.from_hex().expect("could not parse hex string");
let bytes2 = str2.from_hex().expect("could not parse hex string");
let mut vec = Vec::new();
for (a, b) in bytes1.iter().zip(bytes2) {
vec.push(a ... | identifier_body |
main.rs | extern crate rustc_serialize;
use std::fs::File;
use std::io::prelude::*;
use rustc_serialize::hex::{FromHex, ToHex};
fn xor_hex_strings(str1: &str, str2: &str) -> Option<String> {
if str1.len()!= str2.len() {
None
} else {
let bytes1 = str1.from_hex().expect("could not parse hex string");
... | 't' => *score += 9.056,
'u' => *score += 2.758,
'v' => *score += 0.978,
'w' => *score += 2.360,
'x' => *score += 0.150,
'y' => *score += 1.974,
'z' => *score += 0.074,
_ => *score -= 20.0,
}
}
}
fn find_best_phr... | 'r' => *score += 5.987,
's' => *score += 6.327, | random_line_split |
main.rs | extern crate rustc_serialize;
use std::fs::File;
use std::io::prelude::*;
use rustc_serialize::hex::{FromHex, ToHex};
fn | (str1: &str, str2: &str) -> Option<String> {
if str1.len()!= str2.len() {
None
} else {
let bytes1 = str1.from_hex().expect("could not parse hex string");
let bytes2 = str2.from_hex().expect("could not parse hex string");
let mut vec = Vec::new();
for (a, b) in bytes1.it... | xor_hex_strings | identifier_name |
lib.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Translated from include/uapi/linux/usbdevice_fs.h
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use ... | {
pub nports: c_char,
pub port: [u8; 127],
}
pub const USBDEVFS_CAP_ZERO_PACKET: u32 = 0x01;
pub const USBDEVFS_CAP_BULK_CONTINUATION: u32 = 0x02;
pub const USBDEVFS_CAP_NO_PACKET_SIZE_LIM: u32 = 0x04;
pub const USBDEVFS_CAP_BULK_SCATTER_GATHER: u32 = 0x08;
pub const USBDEVFS_CAP_REAP_AFTER_DISCONNECT: u32 = ... | usbdevfs_hub_portinfo | identifier_name |
lib.rs | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Translated from include/uapi/linux/usbdevice_fs.h
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
use ... | pub num_streams: c_uint,
pub num_eps: c_uint,
pub eps: __IncompleteArrayField<c_char>,
}
const U: u32 = 'U' as u32;
ioctl_iowr_nr!(USBDEVFS_CONTROL, U, 0, usbdevfs_ctrltransfer);
ioctl_iowr_nr!(USBDEVFS_BULK, U, 2, usbdevfs_bulktransfer);
ioctl_ior_nr!(USBDEVFS_RESETEP, U, 3, c_uint);
ioctl_ior_nr!(USBDEV... | }
#[repr(C)]
pub struct usbdevfs_streams { | random_line_split |
promote-not.rs | // ignore-tidy-linelength
// Test various things that we do not want to promote.
#![allow(unconditional_panic, const_err)]
use std::cell::Cell;
// We do not promote mutable references.
static mut TEST1: Option<&mut [i32]> = Some(&mut [1, 2, 3]); //~ ERROR temporary value dropped while borrowed
static mut TEST2: &'st... | }
// We do not promote union field accesses in `fn.
union U { x: i32, y: i32 }
pub const fn promote_union() {
let _x: &'static i32 = &unsafe { U { x: 0 }.x }; //~ ERROR temporary value dropped while borrowed
}
// We do not promote union field accesses in `const`, either.
const TEST_UNION: () = {
let _x: &'sta... | }
13 | random_line_split |
promote-not.rs | // ignore-tidy-linelength
// Test various things that we do not want to promote.
#![allow(unconditional_panic, const_err)]
use std::cell::Cell;
// We do not promote mutable references.
static mut TEST1: Option<&mut [i32]> = Some(&mut [1, 2, 3]); //~ ERROR temporary value dropped while borrowed
static mut TEST2: &'st... |
13
}
// We do not promote union field accesses in `fn.
union U { x: i32, y: i32 }
pub const fn promote_union() {
let _x: &'static i32 = &unsafe { U { x: 0 }.x }; //~ ERROR temporary value dropped while borrowed
}
// We do not promote union field accesses in `const`, either.
const TEST_UNION: () = {
let _... | {
let _x: &'static () = &foo(); //~ ERROR temporary value dropped while borrowed
} | conditional_block |
promote-not.rs | // ignore-tidy-linelength
// Test various things that we do not want to promote.
#![allow(unconditional_panic, const_err)]
use std::cell::Cell;
// We do not promote mutable references.
static mut TEST1: Option<&mut [i32]> = Some(&mut [1, 2, 3]); //~ ERROR temporary value dropped while borrowed
static mut TEST2: &'st... |
if b {
let _x: &'static () = &foo(); //~ ERROR temporary value dropped while borrowed
}
13
}
// We do not promote union field accesses in `fn.
union U { x: i32, y: i32 }
pub const fn promote_union() {
let _x: &'static i32 = &unsafe { U { x: 0 }.x }; //~ ERROR temporary value dropped while bor... | { [()][42] } | identifier_body |
promote-not.rs | // ignore-tidy-linelength
// Test various things that we do not want to promote.
#![allow(unconditional_panic, const_err)]
use std::cell::Cell;
// We do not promote mutable references.
static mut TEST1: Option<&mut [i32]> = Some(&mut [1, 2, 3]); //~ ERROR temporary value dropped while borrowed
static mut TEST2: &'st... | () {
let _x: &'static i32 = &unsafe { U { x: 0 }.x }; //~ ERROR temporary value dropped while borrowed
}
// We do not promote union field accesses in `const`, either.
const TEST_UNION: () = {
let _x: &'static i32 = &unsafe { U { x: 0 }.x }; //~ ERROR temporary value dropped while borrowed
};
// In a `const`, ... | promote_union | identifier_name |
http_loader.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 resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt};
use log;
use std::collec... |
fn send_error(url: Url, err: String, start_chan: Sender<LoadResponse>) {
match start_sending_opt(start_chan, Metadata::default(url)) {
Ok(p) => p.send(Done(Err(err))),
_ => {}
};
}
fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
// FIXME: At the time of writing this FIXME... | {
spawn_named("http_loader", proc() load(load_data, start_chan))
} | identifier_body |
http_loader.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 resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt};
use log;
use std::collec... | (url: Url, err: String, start_chan: Sender<LoadResponse>) {
match start_sending_opt(start_chan, Metadata::default(url)) {
Ok(p) => p.send(Done(Err(err))),
_ => {}
};
}
fn load(load_data: LoadData, start_chan: Sender<LoadResponse>) {
// FIXME: At the time of writing this FIXME, servo didn't ... | send_error | identifier_name |
http_loader.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 resource_task::{Metadata, Payload, Done, LoadResponse, LoadData, start_sending_opt};
use log;
use std::collections::HashSet;
use http::client::{RequestWriter, NetworkStream};
use http::headers::HeaderEnum;
use std::io::Reader;
use servo_util::task::sp... | random_line_split | |
test.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... |
None => true
}
})
}
fn should_fail(i: @ast::Item) -> bool {
attr::contains_name(i.attrs.as_slice(), "should_fail")
}
fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod {
let testmod = mk_test_module(cx);
ast::Mod {
items: m.items.clone().append_one(testmod),
... | {
attr::test_cfg(cx.config.as_slice(), cfgs.iter().map(|x| *x))
} | conditional_block |
test.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... | (i: @ast::Item) -> bool {
attr::contains_name(i.attrs.as_slice(), "should_fail")
}
fn add_test_module(cx: &TestCtxt, m: &ast::Mod) -> ast::Mod {
let testmod = mk_test_module(cx);
ast::Mod {
items: m.items.clone().append_one(testmod),
..(*m).clone()
}
}
/*
We're going to be building a m... | should_fail | identifier_name |
test.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... | }
// Traverse the crate, collecting all the test functions, eliding any
// existing main functions, and synthesizing a main test harness
pub fn modify_for_testing(sess: &Session,
krate: ast::Crate) -> ast::Crate {
// We generate the test harness when building in the 'test'
// configur... | is_test_crate: bool,
config: ast::CrateConfig, | random_line_split |
test.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... |
if has_bench_attr &&!has_test_signature(i) {
let sess = cx.sess;
sess.span_err(i.span, "functions used as benches must have signature \
`fn(&mut Bencher) -> ()`");
}
return has_bench_attr && has_test_signature(i);
}
fn is_ignored(cx: &TestCtxt, i: @ast::Item) -> boo... | {
match i.node {
ast::ItemFn(ref decl, _, _, ref generics, _) => {
let input_cnt = decl.inputs.len();
let no_output = match decl.output.node {
ast::TyNil => true,
_ => false
};
let tparm_cnt = gen... | identifier_body |
unique-in-vec-copy.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 ... | assert_eq!(**a.get(0), 20);
assert_eq!(**b.get(0), 10);
} | random_line_split | |
unique-in-vec-copy.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 mut a = vec!(~10);
let b = a.clone();
assert_eq!(**a.get(0), 10);
assert_eq!(**b.get(0), 10);
// This should only modify the value in a, not b
**a.get_mut(0) = 20;
assert_eq!(**a.get(0), 20);
assert_eq!(**b.get(0), 10);
} | identifier_body | |
unique-in-vec-copy.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 mut a = vec!(~10);
let b = a.clone();
assert_eq!(**a.get(0), 10);
assert_eq!(**b.get(0), 10);
// This should only modify the value in a, not b
**a.get_mut(0) = 20;
assert_eq!(**a.get(0), 20);
assert_eq!(**b.get(0), 10);
}
| main | identifier_name |
output_merger.rs | //! Output Merger (OM) stage description.
//! The final stage in a pipeline that creates pixel colors from
//! the input shader results, depth/stencil information, etc.
use crate::pso::{graphics::StencilValue, State};
/// A pixel-wise comparison function.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, Partial... |
}
/// PSO depth-stencil target descriptor.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct DepthStencilDesc {
/// Optional depth testing/writing.
pub depth: Option<DepthTest>,
/// Enable depth bounds testing.
pub dep... | {
StencilTest {
faces: Sided::default(),
read_masks: State::Static(Sided::new(!0)),
write_masks: State::Static(Sided::new(!0)),
reference_values: State::Static(Sided::new(0)),
}
} | identifier_body |
output_merger.rs | //! Output Merger (OM) stage description.
//! The final stage in a pipeline that creates pixel colors from
//! the input shader results, depth/stencil information, etc.
use crate::pso::{graphics::StencilValue, State};
/// A pixel-wise comparison function.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, Partial... | (&self) -> bool {
self.depth.is_some() || self.depth_bounds
}
/// Returns true if the descriptor assumes the stencil attachment.
pub fn uses_stencil(&self) -> bool {
self.stencil.is_some()
}
}
bitflags!(
/// Face.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
... | uses_depth | identifier_name |
output_merger.rs | //! Output Merger (OM) stage description.
//! The final stage in a pipeline that creates pixel colors from
//! the input shader results, depth/stencil information, etc.
use crate::pso::{graphics::StencilValue, State};
/// A pixel-wise comparison function.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, Partial... | /// Source and destination are multiplied by factors before subtraction.
Sub { src: Factor, dst: Factor },
/// Subtracts source from destination.
/// Source and destination are multiplied by factors before subtraction.
RevSub { src: Factor, dst: Factor },
/// Component-wise minimum value of sour... | pub enum BlendOp {
/// Adds source and destination.
/// Source and destination are multiplied by factors before addition.
Add { src: Factor, dst: Factor },
/// Subtracts destination from source. | random_line_split |
session.rs | //! Defines the interface for the session-level management of HTTP/2
//! communication. This is effectively an API that allows hooking into an
//! HTTP/2 connection in order to handle events arising on the connection.
//!
//! The module also provides a default implementation for some of the traits.
use std::collections... | () {
fn new_mock_state() -> DefaultSessionState<TestStream> { DefaultSessionState::new() }
{
// Test insert
let mut state = new_mock_state();
state.insert_stream(Stream::new(1));
assert_eq!(state.get_stream_ref(1).unwrap().id(), 1);
}
{
... | test_default_session_state | identifier_name |
session.rs | //! Defines the interface for the session-level management of HTTP/2
//! communication. This is effectively an API that allows hooking into an
//! HTTP/2 connection in order to handle events arising on the connection.
//!
//! The module also provides a default implementation for some of the traits.
use std::collections... | impl DefaultStream {
/// Create a new `DefaultStream` with the given ID.
pub fn new(stream_id: StreamId) -> DefaultStream {
DefaultStream {
stream_id: stream_id,
headers: None,
body: Vec::new(),
state: StreamState::Open,
data: None,
}
... | }
| random_line_split |
session.rs | //! Defines the interface for the session-level management of HTTP/2
//! communication. This is effectively an API that allows hooking into an
//! HTTP/2 connection in order to handle events arising on the connection.
//!
//! The module also provides a default implementation for some of the traits.
use std::collections... | else {
StreamDataChunk::Chunk(read)
}
}
};
// Transition the stream state to locally closed if we've extracted the final data chunk.
match chunk {
StreamDataChunk::Last(_) => self.close_local(),
_ => {},
};
... | {
StreamDataChunk::Last(read)
} | conditional_block |
session.rs | //! Defines the interface for the session-level management of HTTP/2
//! communication. This is effectively an API that allows hooking into an
//! HTTP/2 connection in order to handle events arising on the connection.
//!
//! The module also provides a default implementation for some of the traits.
use std::collections... |
{
// Test insert
let mut state = new_mock_state();
state.insert_stream(Stream::new(1));
assert_eq!(state.get_stream_ref(1).unwrap().id(), 1);
}
{
// Test remove
let mut state = new_mock_state();
state.insert_st... | { DefaultSessionState::new() } | identifier_body |
issue-2904.rs | // build-pass
#![allow(unused_must_use)]
#![allow(dead_code)]
#![allow(unused_mut)]
#![allow(non_camel_case_types)]
// Map representation
use std::fmt;
use std::io::prelude::*;
use square::{bot, wall, rock, lambda, closed_lift, open_lift, earth, empty};
enum square {
bot,
wall,
rock,
lambda,
clos... |
'\\' => { lambda }
'L' => { closed_lift }
'O' => { open_lift }
'.' => { earth }
'' => { empty }
_ => {
println!("invalid square: {}", c);
panic!()
}
}
}
fn read_board_grid<rdr:'static + Read>(mut input: rdr)
-> Vec<Vec<square>> {
... | { rock } | conditional_block |
issue-2904.rs | // build-pass
#![allow(unused_must_use)]
#![allow(dead_code)]
#![allow(unused_mut)]
#![allow(non_camel_case_types)]
// Map representation
use std::fmt;
use std::io::prelude::*;
use square::{bot, wall, rock, lambda, closed_lift, open_lift, earth, empty};
enum square {
bot,
wall,
rock,
lambda,
clos... | <rdr:'static + Read>(mut input: rdr)
-> Vec<Vec<square>> {
let mut input: &mut dyn Read = &mut input;
let mut grid = Vec::new();
let mut line = [0; 10];
input.read(&mut line);
let mut row = Vec::new();
for c in &line {
row.push(square_from_char(*c as char))
}
g... | read_board_grid | identifier_name |
issue-2904.rs | // build-pass
#![allow(unused_must_use)]
#![allow(dead_code)]
#![allow(unused_mut)]
#![allow(non_camel_case_types)]
// Map representation
use std::fmt;
use std::io::prelude::*;
use square::{bot, wall, rock, lambda, closed_lift, open_lift, earth, empty};
enum square {
bot,
wall,
rock,
lambda,
clos... | panic!()
}
}
}
fn read_board_grid<rdr:'static + Read>(mut input: rdr)
-> Vec<Vec<square>> {
let mut input: &mut dyn Read = &mut input;
let mut grid = Vec::new();
let mut line = [0; 10];
input.read(&mut line);
let mut row = Vec::new();
for c in &line {
... | random_line_split | |
app_bluenrg_stm32l1.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
//! Sample application for BlueNRG communication over SPI in X-NUCLEO-IDB04A1
//! extension board for NUCLEO-L152RE
#[macro_use] #[plugin]
extern crate core;
extern crate zinc;
use core::intrinsics::abort;
// "curious module hack" - a workaround for `fmt` mod... | use core::fmt::Writer;
use core::result::Result;
use zinc::drivers::bluenrg;
use zinc::hal;
use zinc::hal::pin::Gpio;
use zinc::hal::stm32l1::{init, pin, spi, usart};
zinc::hal::mem_init::init_stack();
zinc::hal::mem_init::init_data();
let sys_clock = init::ClockConfig::new_default();
sys_clock.se... | }
#[no_mangle]
pub unsafe fn main() { | random_line_split |
app_bluenrg_stm32l1.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
//! Sample application for BlueNRG communication over SPI in X-NUCLEO-IDB04A1
//! extension board for NUCLEO-L152RE
#[macro_use] #[plugin]
extern crate core;
extern crate zinc;
use core::intrinsics::abort;
// "curious module hack" - a workaround for `fmt` mod... |
let mut uart = usart::Usart::new(usart::UsartPeripheral::Usart2, 38400, usart::WordLen::WordLen8bits,
hal::uart::Parity::Disabled, usart::StopBit::StopBit1bit, &sys_clock);
let _ = write!(&mut uart, "BlueNRG test app for STM32L1\n");
let _spi_clock = pin::Pin::new(pin::Port::PortB, 3,
pin::Mode::AltFunc... | {
use core::fmt::Writer;
use core::result::Result;
use zinc::drivers::bluenrg;
use zinc::hal;
use zinc::hal::pin::Gpio;
use zinc::hal::stm32l1::{init, pin, spi, usart};
zinc::hal::mem_init::init_stack();
zinc::hal::mem_init::init_data();
let sys_clock = init::ClockConfig::new_default();
sys_clock.... | identifier_body |
app_bluenrg_stm32l1.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
//! Sample application for BlueNRG communication over SPI in X-NUCLEO-IDB04A1
//! extension board for NUCLEO-L152RE
#[macro_use] #[plugin]
extern crate core;
extern crate zinc;
use core::intrinsics::abort;
// "curious module hack" - a workaround for `fmt` mod... | (h: u8) -> &'static str {
match h {
0x0 => "0",
0x1 => "1",
0x2 => "2",
0x3 => "3",
0x4 => "4",
0x5 => "5",
0x6 => "6",
0x7 => "7",
0x8 => "8",
0x9 => "9",
0xA => "A",
0xB => "B",
0xC => "C",
0xD => "D"... | map_hex | identifier_name |
app_bluenrg_stm32l1.rs | #![feature(plugin)]
#![crate_type="staticlib"]
#![no_std]
//! Sample application for BlueNRG communication over SPI in X-NUCLEO-IDB04A1
//! extension board for NUCLEO-L152RE
#[macro_use] #[plugin]
extern crate core;
extern crate zinc;
use core::intrinsics::abort;
// "curious module hack" - a workaround for `fmt` mod... | ,
Result::Err(bluenrg::Error::Sleeping) => {
write!(&mut uart, "BlueNRG is sleeping\n");
},
Result::Err(bluenrg::Error::Allocating) => {
write!(&mut uart, "BlueNRG is allocating buffers\n");
},
Result::Err(bluenrg::Error::Unknown(status)) => {
let status_s = map_byte(status);
... | {
let size_write_s = map_byte(size_write as u8);
let size_read_s = map_byte(size_read as u8);
write!(&mut uart,
"BlueNRG is ready, write size = {}{}, read size = {}{}\n",
size_write_s.0, size_write_s.1, size_read_s.0, size_read_s.1);
} | conditional_block |
util.rs | use num::{Zero, One};
use ga::Array;
use graph::Graph;
pub fn one_hot_row<N, M>(label: N, classes: N) -> Array<M>
where usize: From<N>,
M: Clone+Zero+One,
{
let classes: usize = From::from(classes); // Cast class count to usize
let label: usize = From::from(label); // Cast label to usize
... |
pub fn argmax_rows(a: &Array<f32>, out: &mut Array<usize>) {
let (rows, columns) = (a.shape()[0], a.shape()[1]);
for row in 0..rows {
// TODO: I would do this:
// let max_col = (0..a.columns()).max_by_key(|col| a[&[row, *col]]);
// But f32 does not implement Ord :'(
let (mut ma... | {
let classes: usize = From::from(classes); // Cast class count to usize
let batch_size = labels.len();
let mut one_hot_batch = Array::new(vec![batch_size, classes], Zero::zero()); // Construct the array
// Set the one hot components
for b in 0..batch_size {
one_hot_batch[&[b, From::from(lab... | identifier_body |
util.rs | use num::{Zero, One};
use ga::Array;
use graph::Graph;
pub fn one_hot_row<N, M>(label: N, classes: N) -> Array<M>
where usize: From<N>,
M: Clone+Zero+One,
{
let classes: usize = From::from(classes); // Cast class count to usize
let label: usize = From::from(label); // Cast label to usize
... |
}
out[&[row]] = max_col;
}
}
pub fn unrolled_net<F, I, O>(graph: &mut Graph, unroll_steps: usize, first_inputs: I, mut net_step: F) -> (I, Vec<O>)
where F: FnMut(&mut Graph, I) -> (I, O),
{
let mut next_inputs = first_inputs;
let mut steps = vec![];
for _ in 0..unr... | {
max_col = col;
max_val = val;
} | conditional_block |
util.rs | use num::{Zero, One};
use ga::Array;
use graph::Graph;
pub fn one_hot_row<N, M>(label: N, classes: N) -> Array<M>
where usize: From<N>,
M: Clone+Zero+One,
{
let classes: usize = From::from(classes); // Cast class count to usize
let label: usize = From::from(label); // Cast label to usize
... | <N, M>(labels: &[N], classes: N) -> Array<M>
where usize: From<N>,
N: Copy,
M: Clone+Zero+One,
{
let classes: usize = From::from(classes); // Cast class count to usize
let batch_size = labels.len();
let mut one_hot_batch = Array::new(vec![batch_size, classes], Zero::zero()); ... | one_hot_rows_batch | identifier_name |
util.rs | use num::{Zero, One};
use ga::Array;
use graph::Graph;
pub fn one_hot_row<N, M>(label: N, classes: N) -> Array<M>
where usize: From<N>,
M: Clone+Zero+One,
{
let classes: usize = From::from(classes); // Cast class count to usize
let label: usize = From::from(label); // Cast label to usize
... | } | random_line_split | |
picking.rs | #[macro_use]
extern crate glium;
#[allow(unused_imports)]
use glium::{glutin, Surface};
mod support;
#[derive(Copy, Clone, Debug)]
struct PerInstance {
pub id: u32,
pub w_position: (f32, f32, f32),
pub color: (f32, f32, f32),
}
implement_vertex!(PerInstance, id, w_position, color);
fn main() {
// bu... | }
};
action
});
} | }
ev => camera.process_input(&ev),
},
_ => (), | random_line_split |
picking.rs | #[macro_use]
extern crate glium;
#[allow(unused_imports)]
use glium::{glutin, Surface};
mod support;
#[derive(Copy, Clone, Debug)]
struct | {
pub id: u32,
pub w_position: (f32, f32, f32),
pub color: (f32, f32, f32),
}
implement_vertex!(PerInstance, id, w_position, color);
fn main() {
// building the display, ie. the main object
let event_loop = glutin::event_loop::EventLoop::new();
let wb = glutin::window::WindowBuilder::new();
... | PerInstance | identifier_name |
picking.rs | #[macro_use]
extern crate glium;
#[allow(unused_imports)]
use glium::{glutin, Surface};
mod support;
#[derive(Copy, Clone, Debug)]
struct PerInstance {
pub id: u32,
pub w_position: (f32, f32, f32),
pub color: (f32, f32, f32),
}
implement_vertex!(PerInstance, id, w_position, color);
fn main() {
// bu... |
} else {
picking_pbo.write(&[0]);
}
let mut action = support::Action::Continue;
// polling and handling the events received by the window
for event in events {
match event {
glutin::event::Event::WindowEvent { event,.. } => match event {... | {
picking_pbo.write(&[0]);
} | conditional_block |
utils.rs | use anyhow::Result;
use atty::Stream;
use std::fs::OpenOptions;
use std::io::Read;
use std::path::Path;
use std::process::exit;
use crate::file_utils;
use crate::report::*;
pub fn check_input_file(input_file: &Path, report: &Report) {
if!file_utils::file_exists(input_file) {
report.fatal(&format!("Couldn'... |
/// This trys to read the start of input_path to see
/// if it's xml. If there are any problems reading the file
/// then it fails silently.
pub fn check_not_xml(input_file: &Path, report: &Report) {
let _ = check_not_xml_(input_file, report);
}
//---------------------------------------
| {
let mut file = OpenOptions::new().read(true).open(input_file)?;
let mut data = vec![0; 16];
file.read_exact(&mut data)?;
if is_xml(&data) {
report.fatal("This looks like XML. This tool only checks the binary metadata format.");
}
Ok(())
} | identifier_body |
utils.rs | use anyhow::Result;
use atty::Stream;
use std::fs::OpenOptions;
use std::io::Read;
use std::path::Path;
use std::process::exit;
use crate::file_utils;
use crate::report::*;
pub fn check_input_file(input_file: &Path, report: &Report) {
if!file_utils::file_exists(input_file) {
report.fatal(&format!("Couldn'... | (line: &[u8]) -> bool {
line.starts_with(b"<superblock") || line.starts_with(b"?xml") || line.starts_with(b"<!DOCTYPE")
}
pub fn check_not_xml_(input_file: &Path, report: &Report) -> Result<()> {
let mut file = OpenOptions::new().read(true).open(input_file)?;
let mut data = vec![0; 16];
file.read_exact... | is_xml | identifier_name |
utils.rs | use anyhow::Result;
use atty::Stream;
use std::fs::OpenOptions;
use std::io::Read;
use std::path::Path;
use std::process::exit;
use crate::file_utils;
use crate::report::*;
pub fn check_input_file(input_file: &Path, report: &Report) {
if!file_utils::file_exists(input_file) {
report.fatal(&format!("Couldn'... | }
}
fn is_xml(line: &[u8]) -> bool {
line.starts_with(b"<superblock") || line.starts_with(b"?xml") || line.starts_with(b"<!DOCTYPE")
}
pub fn check_not_xml_(input_file: &Path, report: &Report) -> Result<()> {
let mut file = OpenOptions::new().read(true).open(input_file)?;
let mut data = vec![0; 16];
... | Arc::new(mk_progress_bar_report())
} else {
Arc::new(mk_simple_report()) | random_line_split |
utils.rs | use anyhow::Result;
use atty::Stream;
use std::fs::OpenOptions;
use std::io::Read;
use std::path::Path;
use std::process::exit;
use crate::file_utils;
use crate::report::*;
pub fn check_input_file(input_file: &Path, report: &Report) {
if!file_utils::file_exists(input_file) {
report.fatal(&format!("Couldn'... |
}
fn is_xml(line: &[u8]) -> bool {
line.starts_with(b"<superblock") || line.starts_with(b"?xml") || line.starts_with(b"<!DOCTYPE")
}
pub fn check_not_xml_(input_file: &Path, report: &Report) -> Result<()> {
let mut file = OpenOptions::new().read(true).open(input_file)?;
let mut data = vec![0; 16];
fi... | {
Arc::new(mk_simple_report())
} | conditional_block |
vte.rs | use libc::c_char;
use libc::c_void;
use libc::size_t;
use std::cell::RefCell;
use std::ptr;
use std::rc::Rc;
use std::slice;
use std::sync::mpsc::{Sender, Receiver, channel};
use ::tsm::*;
pub struct Vte {
// TODO: remove pub here once all api methods are implemented
pub ptr: *mut TsmVte,
// I'm trying t... | unsafe { tsm_vte_input(self.ptr, bytes.as_ptr(), bytes.len() as size_t ); }
}
}
impl Drop for Vte {
fn drop(&mut self) {
unsafe { tsm_vte_unref(self.ptr) }
}
} | unsafe { tsm_vte_handle_keyboard(self.ptr, 0, 0, 0, ch as u32); }
}
// Not even sure what this does. Is it a sink for the ptys output?
pub fn input(&mut self, bytes: &[u8]) { | random_line_split |
vte.rs | use libc::c_char;
use libc::c_void;
use libc::size_t;
use std::cell::RefCell;
use std::ptr;
use std::rc::Rc;
use std::slice;
use std::sync::mpsc::{Sender, Receiver, channel};
use ::tsm::*;
pub struct Vte {
// TODO: remove pub here once all api methods are implemented
pub ptr: *mut TsmVte,
// I'm trying t... |
}
impl Drop for Vte {
fn drop(&mut self) {
unsafe { tsm_vte_unref(self.ptr) }
}
}
| {
unsafe { tsm_vte_input(self.ptr, bytes.as_ptr(), bytes.len() as size_t ); }
} | identifier_body |
vte.rs | use libc::c_char;
use libc::c_void;
use libc::size_t;
use std::cell::RefCell;
use std::ptr;
use std::rc::Rc;
use std::slice;
use std::sync::mpsc::{Sender, Receiver, channel};
use ::tsm::*;
pub struct | {
// TODO: remove pub here once all api methods are implemented
pub ptr: *mut TsmVte,
// I'm trying to use the rust feature that best reflects the reality that libtsm's vte ptr
// mutates the screen in c-land.
pub screen: Rc<RefCell<::Screen>>,
tx: Box<Sender<char>>,
pub rx: Receiver<char>... | Vte | identifier_name |
find.rs | use std;
use walkdir::WalkDir;
/// Recursively finds tests for the given paths.
pub fn in_paths<'a,P>(paths: P) -> Result<Vec<String>,String>
where P: IntoIterator<Item=&'a str> {
let mut tests = Vec::new();
for path in paths.into_iter() {
let path_tests = try!(in_path(path));
tests.extend... | (path: &str) -> Result<Vec<String>,String> {
let mut dir_tests = Vec::new();
for entry in WalkDir::new(path) {
let entry = entry.unwrap();
// don't go into an infinite loop
if entry.path().to_str().unwrap() == path {
continue;
}
if entry.metadata().unwrap()... | find_files_in_dir | identifier_name |
find.rs | use std;
use walkdir::WalkDir;
/// Recursively finds tests for the given paths.
pub fn in_paths<'a,P>(paths: P) -> Result<Vec<String>,String>
where P: IntoIterator<Item=&'a str> {
let mut tests = Vec::new();
for path in paths.into_iter() {
let path_tests = try!(in_path(path));
tests.extend... |
fn find_tests_in_dir(path: &str) -> Result<Vec<String>,String> {
let tests = try!(find_files_in_dir(path)).into_iter()
.filter(|f| f.ends_with(".ir"))
.collect();
Ok(tests)
}
fn find_files_in_dir(path: &str) -> Result<Vec<String>,String> {
let mut dir_tests = Vec::... | {
let metadata = match std::fs::metadata(path) {
Ok(meta) => meta,
Err(e) => return Err(format!("failed to open '{}': {}",
path, e)),
};
if metadata.is_dir() {
find_tests_in_dir(path)
} else {
Ok(vec![path.to_owned()])
}
} | identifier_body |
find.rs | use std;
use walkdir::WalkDir;
/// Recursively finds tests for the given paths.
pub fn in_paths<'a,P>(paths: P) -> Result<Vec<String>,String>
where P: IntoIterator<Item=&'a str> {
let mut tests = Vec::new();
for path in paths.into_iter() {
let path_tests = try!(in_path(path));
tests.extend... |
}
fn find_tests_in_dir(path: &str) -> Result<Vec<String>,String> {
let tests = try!(find_files_in_dir(path)).into_iter()
.filter(|f| f.ends_with(".ir"))
.collect();
Ok(tests)
}
fn find_files_in_dir(path: &str) -> Result<Vec<String>,String> {
let mut dir_tests = Vec... | {
Ok(vec![path.to_owned()])
} | conditional_block |
find.rs | use std;
use walkdir::WalkDir;
/// Recursively finds tests for the given paths.
pub fn in_paths<'a,P>(paths: P) -> Result<Vec<String>,String>
where P: IntoIterator<Item=&'a str> {
let mut tests = Vec::new();
for path in paths.into_iter() {
let path_tests = try!(in_path(path));
tests.extend... | if entry.path().to_str().unwrap() == path {
continue;
}
if entry.metadata().unwrap().is_file() {
dir_tests.push(entry.path().to_str().unwrap().to_owned());
}
}
Ok(dir_tests)
} |
// don't go into an infinite loop | random_line_split |
image_list_store.rs | /*
* niepce - niepce/ui/image_list_store.rs
*
* Copyright (C) 2020-2021 Hubert Figuière
*
* 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 3 of the License, or
* (at your o... | ) -> *mut ImageListStore {
let box_ = Box::new(ImageListStore::new());
Box::into_raw(box_)
}
/// # Safety
/// Dereference pointer.
#[no_mangle]
pub unsafe extern "C" fn npc_image_list_store_delete(self_: *mut ImageListStore) {
assert!(!self_.is_null());
Box::from_raw(self_);
}
/// Return the gobj for ... | pc_image_list_store_new( | identifier_name |
image_list_store.rs | /*
* niepce - niepce/ui/image_list_store.rs
*
* Copyright (C) 2020-2021 Hubert Figuière
*
* 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 3 of the License, or
* (at your o... | true
}
MetadataChanged(ref m) => {
dbg_out!("metadata changed {:?}", m.meta);
// only interested in a few props
if Self::is_property_interesting(m.meta) {
if let Some(iter) = self.idmap.get(&m.id) {
... | );
} | random_line_split |
image_list_store.rs | /*
* niepce - niepce/ui/image_list_store.rs
*
* Copyright (C) 2020-2021 Hubert Figuière
*
* 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 3 of the License, or
* (at your o... |
fn clear_content(&mut self) {
// clear the map before the list.
self.idmap.clear();
self.store.clear();
}
fn add_libfile(&mut self, f: &LibFile) {
let icon = self.get_loading_icon().cloned();
let iter = self.add_row(
icon.as_ref(),
f,
... |
self.idmap.get(&id)
}
| identifier_body |
image_list_store.rs | /*
* niepce - niepce/ui/image_list_store.rs
*
* Copyright (C) 2020-2021 Hubert Figuière
*
* 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 3 of the License, or
* (at your o... | }
0
}
pub fn get_file(&self, id: LibraryId) -> Option<LibFile> {
if let Some(iter) = self.idmap.get(&id) {
self.store
.value(&iter, ColIndex::File as i32)
.get::<&StoreLibFile>()
.map(|v| v.0.clone())
.ok()
... |
return libfile.0.id();
}
| conditional_block |
mod.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_eq!(ten.rem(&two), cast(0i).unwrap());
assert_eq!(ten.add(&two), ten + two);
assert_eq!(ten.sub(&two), ten - two);
assert_eq!(ten.mul(&two), ten * two);
assert_eq!(ten.div(&two), ten / two);
assert_eq!(ten.rem(&two), ten % two);
} | assert_eq!(ten.div(&two), cast(5i).unwrap()); | random_line_split |
mod.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T>(ten: T, two: T) where
T: PartialEq + NumCast
+ Add<T, T> + Sub<T, T>
+ Mul<T, T> + Div<T, T>
+ Rem<T, T> + Show
{
assert_eq!(ten.add(&two), cast(12i).unwrap());
assert_eq!(ten.sub(&two), cast(8i).unwrap());
assert_eq!(ten.mul(&two), cast(20i).unwrap());
assert_eq!(ten.div(&two)... | test_num | identifier_name |
mod.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_eq!(ten.add(&two), cast(12i).unwrap());
assert_eq!(ten.sub(&two), cast(8i).unwrap());
assert_eq!(ten.mul(&two), cast(20i).unwrap());
assert_eq!(ten.div(&two), cast(5i).unwrap());
assert_eq!(ten.rem(&two), cast(0i).unwrap());
assert_eq!(ten.add(&two), ten + two);
assert_eq!(te... | identifier_body | |
value.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 ... | (self) -> bool {
unsafe {
llvm::LLVMIsATerminatorInst(self.get()).is_not_null()
}
}
}
pub struct Use(UseRef);
/**
* Wrapper for LLVM UseRef
*/
impl Use {
pub fn get(&self) -> UseRef {
let Use(v) = *self; v
}
pub fn get_user(self) -> Value {
unsafe {
... | is_a_terminator_inst | identifier_name |
value.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 current = self.next;
self.next = current.and_then(|u| u.get_next_use());
current.map(|u| u.get_user())
} | identifier_body |
value.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 ... | _ => None
}
}
/// Returns an iterator for the users of this value
pub fn user_iter(self) -> Users {
Users {
next: self.get_first_use()
}
}
/// Returns the requested operand of this instruction
/// Returns None, if there's no operand at the given ... | random_line_split | |
issue-27949.rs | // run-pass
//
// At one time, the `==` operator (and other binary operators) did not
// support subtyping during type checking, and would therefore require
// LHS and RHS to be exactly identical--i.e. to have the same lifetimes.
//
// This was fixed in 1a7fb7dc78439a704f024609ce3dc0beb1386552.
#[derive(Copy, Clone)]
... | fn eq(&self, other: &Input<'a>) -> bool {
self.foo == other.foo
}
fn ne(&self, other: &Input<'a>) -> bool {
self.foo!= other.foo
}
}
fn check_equal<'a, 'b>(x: Input<'a>, y: Input<'b>) -> bool {
// Type checking error due to 'a!= 'b prior to 1a7fb7dc78
x == y
}
fn main() {
... | impl <'a> std::cmp::PartialEq<Input<'a>> for Input<'a> { | random_line_split |
issue-27949.rs | // run-pass
//
// At one time, the `==` operator (and other binary operators) did not
// support subtyping during type checking, and would therefore require
// LHS and RHS to be exactly identical--i.e. to have the same lifetimes.
//
// This was fixed in 1a7fb7dc78439a704f024609ce3dc0beb1386552.
#[derive(Copy, Clone)]
... |
fn ne(&self, other: &Input<'a>) -> bool {
self.foo!= other.foo
}
}
fn check_equal<'a, 'b>(x: Input<'a>, y: Input<'b>) -> bool {
// Type checking error due to 'a!= 'b prior to 1a7fb7dc78
x == y
}
fn main() {
let i = 1u32;
let j = 1u32;
let k = 2u32;
let input_i = Input { foo... | {
self.foo == other.foo
} | identifier_body |
issue-27949.rs | // run-pass
//
// At one time, the `==` operator (and other binary operators) did not
// support subtyping during type checking, and would therefore require
// LHS and RHS to be exactly identical--i.e. to have the same lifetimes.
//
// This was fixed in 1a7fb7dc78439a704f024609ce3dc0beb1386552.
#[derive(Copy, Clone)]
... | <'a> {
foo: &'a u32
}
impl <'a> std::cmp::PartialEq<Input<'a>> for Input<'a> {
fn eq(&self, other: &Input<'a>) -> bool {
self.foo == other.foo
}
fn ne(&self, other: &Input<'a>) -> bool {
self.foo!= other.foo
}
}
fn check_equal<'a, 'b>(x: Input<'a>, y: Input<'b>) -> bool {
// ... | Input | identifier_name |
whoami.rs | #![crate_name = "whoami"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.21 */
ex... | {
unsafe {
match platform::getusername() {
Ok(username) => println!("{}", username),
Err(err) => match err.raw_os_error() {
Some(0) | None => crash!(1, "failed to get username"),
Some(_) => crash!(1, "failed to get username: {}", err),
}
... | identifier_body | |
whoami.rs | #![crate_name = "whoami"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.21 */
ex... | Ok(m) => m,
Err(f) => crash!(1, "{}", f),
};
if matches.opt_present("help") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTIONS]", NAME);
println!("");
println!("{}", opts.usage("print effective userid"));
... | random_line_split | |
whoami.rs | #![crate_name = "whoami"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.21 */
ex... | (args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "{}", f),
};
if... | uumain | identifier_name |
if-let.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 ... | if let a = 1 { //~ ERROR irrefutable if-let
println!("irrefutable pattern");
} else if true {
println!("else-if in irrefutable if-let");
} else {
println!("else in irrefutable if-let");
}
if let 1 = 2 {
println!("refutable pattern");
} else if let a = 1 { //~ ERR... | if let a = 1 { //~ ERROR irrefutable if-let
println!("irrefutable pattern");
}
| random_line_split |
if-let.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 ... | println!("if");
} else if let a = 1 { //~ ERROR irrefutable if-let
println!("irrefutable pattern");
}
}
| {
if let a = 1 { //~ ERROR irrefutable if-let
println!("irrefutable pattern");
}
if let a = 1 { //~ ERROR irrefutable if-let
println!("irrefutable pattern");
} else if true {
println!("else-if in irrefutable if-let");
} else {
println!("else in irrefutable if-let");
... | identifier_body |
if-let.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 ... | () {
macro_rules! foo{
($p:pat, $e:expr, $b:block) => {{
if let $p = $e $b
}}
}
macro_rules! bar{
($p:pat, $e:expr, $b:block) => {{
foo!($p, $e, $b)
}}
}
foo!(a, 1, { //~ ERROR irrefutable if-let
println!("irrefutable pattern");
})... | macros | identifier_name |
mod.rs | //! Access to open sqlite3 database by filename.
//!
//! The `core` module requires explicit authority to access files and such,
//! following the principle of least authority.
//!
//! This module provides the privileged functions to create such authorities.
//!
//! *TODO: move `mod access` to its own crate so that lin... |
use access::flags::OpenFlags;
// submodule KLUDGE around missing_docs for bitflags!()
#[allow(missing_docs)]
pub mod flags;
/// Open a database by filename.
///
/// *TODO: test for "Note that sqlite3_open() can be used to either
/// open existing database files or to create and open new database
/// files."*
///
///... | random_line_split | |
mod.rs | //! Access to open sqlite3 database by filename.
//!
//! The `core` module requires explicit authority to access files and such,
//! following the principle of least authority.
//!
//! This module provides the privileged functions to create such authorities.
//!
//! *TODO: move `mod access` to its own crate so that lin... | () {
let mut temp_directory = temp_dir();
temp_directory.push("db1");
let path = temp_directory.into_os_string().into_string().unwrap();
DatabaseConnection::new(
ByFilename {
filename: path.as_ref(), flags: Default::default()
})
.unwrap(... | open_file_db | identifier_name |
mod.rs | //! Access to open sqlite3 database by filename.
//!
//! The `core` module requires explicit authority to access files and such,
//! following the principle of least authority.
//!
//! This module provides the privileged functions to create such authorities.
//!
//! *TODO: move `mod access` to its own crate so that lin... |
/// Access to a database by filename
pub struct ByFilename<'a> {
/// Filename or sqlite3 style URI.
pub filename: &'a str,
/// Flags for additional control over the new database connection.
pub flags: OpenFlags
}
impl<'a> Access for ByFilename<'a> {
fn open(self, db: *mut *mut ffi::sqlite3) -> c_... | {
DatabaseConnection::new(
ByFilename {
filename: filename,
flags: flags.unwrap_or_default()
})
} | identifier_body |
zbuffer.rs | use orbclient;
use super::super::geometry;
use super::super::texture;
use std;
pub struct | {
w: u32,
h: u32,
data: Box<[f32]>
}
impl ZBuffer {
pub fn new(width: u32, height: u32) -> Self {
use std::f32;
ZBuffer {
w: width,
h: height,
data: vec![f32::INFINITY; width as usize * height as usize].into_boxed_slice()
}
}
pub... | ZBuffer | identifier_name |
zbuffer.rs | use orbclient;
use super::super::geometry;
use super::super::texture;
use std;
pub struct ZBuffer {
w: u32,
h: u32,
data: Box<[f32]>
}
impl ZBuffer {
pub fn new(width: u32, height: u32) -> Self {
use std::f32;
ZBuffer {
w: width,
h: height,
data: vec... |
}
}
}
}
window.line(x1, y1, x2, y2, color);
window.line(x2, y2, x3, y3, color);
window.line(x3, y3, x1, y1, color);
}
pub fn triangle_s<T: texture::GetColor>(triangle: &geometry::Triangle,
color: orbclient::Color, window: &mut orbcl... | {
window.pixel(x as i32, y as i32, texture.get(alpha, beta, gamma));
buffer.set(x as u32, y as u32, z_now);
} | conditional_block |
zbuffer.rs | use orbclient;
use super::super::geometry;
use super::super::texture;
use std;
pub struct ZBuffer {
w: u32,
h: u32,
data: Box<[f32]>
}
impl ZBuffer {
pub fn new(width: u32, height: u32) -> Self {
use std::f32;
ZBuffer {
w: width,
h: height,
data: vec... |
pub fn clear(&mut self) {
use std::f32;
self.data = vec![f32::INFINITY; self.w as usize * self.h as usize].into_boxed_slice()
}
pub fn draw(&self, window: &mut orbclient::window::Window) {
for x in 0..self.w {
for y in 0..self.h {
let value = se... | {
self.data[x as usize + (self.w * y) as usize]
} | identifier_body |
zbuffer.rs | use orbclient;
use super::super::geometry;
use super::super::texture;
use std;
pub struct ZBuffer {
w: u32,
h: u32,
data: Box<[f32]>
}
impl ZBuffer {
pub fn new(width: u32, height: u32) -> Self {
use std::f32;
ZBuffer {
w: width,
h: height,
data: vec... | let (x2, y2) = screen(x2, y2, scr_width, scr_height);
let (x3, y3) = screen(x3, y3, scr_width, scr_height);
let x_low = min(x1, min(x2, x3));
let x_max = max(x1, max(x2, x3));
let y_low = min(y1, min(y2, y3));
let y_max = max(y1, max(y2, y3));
{
let x1 = x1 as f32;
... | let scr_width = window.width() as i32;
let scr_height = window.height() as i32;
// Change f32 points into drawable i32, based on screen width,
let (x1, y1) = screen(x1, y1, scr_width, scr_height); | random_line_split |
regions-early-bound-trait-param.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 ... | }
}
impl<'t> MakerTrait for Box<Trait<'t>+'static> {
fn mk() -> Box<Trait<'t>+'static> {
let tup: Box<(isize, isize)> = box() (4,5);
tup as Box<Trait>
}
}
enum List<'l> {
Cons(isize, &'l List<'l>),
Null
}
impl<'l> List<'l> {
fn car<'m>(&'m self) -> isize {
match self {... | x
}
fn short<'b>(&'b self) -> isize {
let &(_,y) = self;
y | random_line_split |
regions-early-bound-trait-param.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 t = (2,3);
let o = &t as &Trait;
let s1 = Struct1 { f: o };
let s2 = Struct2 { f: o };
assert_eq!(poly_invoke(&t), (2,3));
assert_eq!(object_invoke1(&t), (2,3));
assert_eq!(field_invoke1(&s1), (2,3));
assert_eq!(object_invoke2(&t), 3);
assert_eq!(field_invoke2... | {
l.cdr()
} | identifier_body |
regions-early-bound-trait-param.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 ... | <'m>(&'m self) -> isize {
match self {
&List::Cons(car, _) => car,
&List::Null => panic!(),
}
}
fn cdr<'n>(&'n self) -> &'l List<'l> {
match self {
&List::Cons(_, cdr) => cdr,
&List::Null => panic!(),
}
}
}
impl<'t> RefMakerTra... | car | identifier_name |
scene.rs | use crate::device::{CorrelatedColorTemperature, DeviceKey, DeviceState};
use super::{
device::{DeviceColor, DeviceId},
group::GroupId,
integration::IntegrationId,
};
use palette::{rgb::Rgb, Hsv, Lch};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
macro_attr! {
#[derive(Clone, Deb... |
#[derive(Clone, Deserialize, Debug, Serialize)]
#[serde(untagged)]
pub enum ColorConfig {
Lch(Lch),
Hsv(Hsv),
Rgb(Rgb),
}
pub fn color_config_as_device_color(color_config: ColorConfig) -> DeviceColor {
DeviceColor::Color(match color_config {
ColorConfig::Lch(lch) => lch.into(),
ColorCo... | SceneId(scene_id)
}
} | random_line_split |
scene.rs | use crate::device::{CorrelatedColorTemperature, DeviceKey, DeviceState};
use super::{
device::{DeviceColor, DeviceId},
group::GroupId,
integration::IntegrationId,
};
use palette::{rgb::Rgb, Hsv, Lch};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
macro_attr! {
#[derive(Clone, Deb... | {
Lch(Lch),
Hsv(Hsv),
Rgb(Rgb),
}
pub fn color_config_as_device_color(color_config: ColorConfig) -> DeviceColor {
DeviceColor::Color(match color_config {
ColorConfig::Lch(lch) => lch.into(),
ColorConfig::Hsv(hsv) => hsv,
ColorConfig::Rgb(rgb) => rgb.into(),
})
}
#[derive(C... | ColorConfig | identifier_name |
packed-tuple-struct-layout.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 s5 = S5(1, 0xff_00_00_ff);
let transd : [u8; 5] = mem::transmute(s5);
// Don't worry about endianness, the u32 is palindromic.
assert_eq!(transd, [1, 0xff, 0, 0, 0xff]);
} | random_line_split |
packed-tuple-struct-layout.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 ... | (u8,u32);
pub fn main() {
unsafe {
let s4 = S4(1, [2,3,4]);
let transd : [u8; 4] = mem::transmute(s4);
assert_eq!(transd, [1, 2, 3, 4]);
let s5 = S5(1, 0xff_00_00_ff);
let transd : [u8; 5] = mem::transmute(s5);
// Don't worry about endianness, the u32 is palindromic... | S5 | identifier_name |
issue-1034.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct __BindgenBitfieldUnit<Storage> {
storage: Storage,
}
impl<Storage> __BindgenBitfieldUnit<Storage> {
#[inline]
... | ;
val |= 1 << index;
}
}
val
}
#[inline]
pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!(
(bit_offset... | {
i
} | conditional_block |
issue-1034.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct __BindgenBitfieldUnit<Storage> {
storage: Storage,
}
impl<Storage> __BindgenBitfieldUnit<Storage> {
#[inline]
... |
#[inline]
pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!(
(bit_offset + (bit_width as usize)) / 8 <=
self.storage.as_ref().len()
... | {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!(
(bit_offset + (bit_width as usize)) / 8 <=
self.storage.as_ref().len()
);
let mut val = 0;
for i in 0..(bit_width as usize) {
... | identifier_body |
issue-1034.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct __BindgenBitfieldUnit<Storage> {
storage: Storage,
}
impl<Storage> __BindgenBitfieldUnit<Storage> {
#[inline]
... | let mask = 1 << bit_index;
if val {
*byte |= mask;
} else {
*byte &=!mask;
}
}
#[inline]
pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().l... | }; | random_line_split |
issue-1034.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct __BindgenBitfieldUnit<Storage> {
storage: Storage,
}
impl<Storage> __BindgenBitfieldUnit<Storage> {
#[inline]
... | () {
assert_eq!(
::std::mem::size_of::<S2>(),
2usize,
concat!("Size of: ", stringify!(S2))
);
assert_eq!(
::std::mem::align_of::<S2>(),
1usize,
concat!("Alignment of ", stringify!(S2))
);
}
impl S2 {
#[inline]
pub fn new_bitfield_1() -> __BindgenBi... | bindgen_test_layout_S2 | identifier_name |
transactions.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | fn new(rt: &Runtime) -> Self {
let channel = NodeChannel::new(&EventsPoolCapacity::default());
let handler = MessagesHandlerRef::new();
let handler_part = HandlerPart {
handler: handler.clone(),
internal_rx: channel.internal_events.1,
network_rx: channel.... | }
impl MessageVerifier { | random_line_split |
transactions.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
fn reset(&self, expected_count: usize) -> oneshot::Receiver<()> {
let (handler, finish_signal) = MessagesHandler::new(expected_count);
*self.inner.write().unwrap() = handler;
finish_signal
}
}
impl EventHandler for MessagesHandlerRef {
fn handle_event(&mut self, event: Event) -> E... | {
let (handler, _) = MessagesHandler::new(0);
MessagesHandlerRef {
inner: Arc::new(RwLock::new(handler)),
}
} | identifier_body |
transactions.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (&mut self, messages: Vec<Vec<u8>>) {
let finish_signal = self.tx_handler.reset(messages.len());
let tx_sender = self.tx_sender.as_mut().unwrap();
let messages = messages
.into_iter()
.map(|raw| Ok(InternalRequest::VerifyMessage(raw)));
tx_sender
.send_al... | send_all | identifier_name |
transactions.rs | // Copyright 2020 The Exonum Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
}
}
EventOutcome::Ok
}
}
fn gen_messages(count: u64, tx_size: usize) -> Vec<Vec<u8>> {
let keypair = crypto::KeyPair::random();
(0..count)
.map(|_| {
let tx = AnyTx::new(CallInfo::new(0, 0), vec![0; tx_size]).sign_with_keypair(&keypair);
tx.into_b... | {
self.finish_signal
.take()
.unwrap()
.send(())
.expect("cannot send finish signal");
} | conditional_block |
requested_path.rs | use iron::Request;
use std::path::{PathBuf, Path};
use std::fs::{self, Metadata};
use std::convert::AsRef;
pub struct RequestedPath {
pub path: PathBuf,
}
impl RequestedPath {
pub fn new<P: AsRef<Path>>(root_path: P, request: &Request) -> RequestedPath {
let mut path = root_path.as_ref().to_path_buf()... |
pub fn should_redirect(&self, metadata: &Metadata, request: &Request) -> bool {
let last_url_element = request.url.path
.last()
.map(|s| s.as_ref());
// As per servo/rust-url/serialize_path, URLs ending in a slash have an
// empty string stored as the last component o... | } | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.