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
blink_ops.rs
/* Copyright 2013 Leon Sixt * * 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 in wr...
(&self) { let tpe = T_ROOT ^ T_LEAF; let root : DefaultBLinkNode<uint, uint, uint> = PhysicalNode::new(tpe, 0u, None, ~[2u],~[0u,1u]); can_contains_range!(root, 0u, 10); assert!(self.can_contain_key(&root, &10000)); let leaf : DefaultBLinkNode...
test_can_contain_key
identifier_name
blink_ops.rs
/* Copyright 2013 Leon Sixt * * 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 in wr...
fn scannode<'a>(&self, node: &'a Node<INODE,LEAF>, key: &K) -> Option<(&'a Ptr, Movement)> { let can_contain = match node { &Leaf(ref leaf) => self.can_contain_key(leaf, key), &INode(ref inode) => self.can_contain_key(inode, key) }; if(! can_contain) { r...
{ if !self.can_contain_key(inode,key) { return None; } let idx = algorithm::bsearch_idx(inode.keys().slice_from(0), key); debug!("[get_ptr] key: {}, ptr: {}, keys: {} values: {}, idx: {}, is_most_right_node: {}, is_root: {}", key.to_str(), inode.my_ptr().to_...
identifier_body
blink_ops.rs
/* Copyright 2013 Leon Sixt * * 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 in wr...
} fn get_ptr<'a>(&self, inode: &'a INODE, key: &K) -> Option<&'a Ptr> { if!self.can_contain_key(inode,key) { return None; } let idx = algorithm::bsearch_idx(inode.keys().slice_from(0), key); debug!("[get_ptr] key: {}, ptr: {}, keys: {} values: {}, idx: {}, is_most_r...
{ None }
conditional_block
connection.rs
use proto; use byteorder::{BigEndian, WriteBytesExt}; use std; use std::net::{IpAddr, TcpStream}; use std::sync::Mutex; use openssl; use openssl::ssl::{HandshakeError, SslContext, SslMethod, SslStream}; use protobuf; // Connect const SSL_HANDSHAKE_RETRIES: u8 = 3; #[derive(Debug)] pub enum ConnectionError { E...
} #[derive(Debug)] pub enum SendError { MessageTooLarge(&'static str), Ssl(openssl::ssl::Error) } // TODO: this should impl error, display impl From<openssl::ssl::Error> for SendError { fn from(e: openssl::ssl::Error) -> Self { SendError::Ssl(e) } } pub struct Connection { control_channe...
{ ConnectionError::TcpStream(e) }
identifier_body
connection.rs
use proto; use byteorder::{BigEndian, WriteBytesExt}; use std; use std::net::{IpAddr, TcpStream}; use std::sync::Mutex; use openssl; use openssl::ssl::{HandshakeError, SslContext, SslMethod, SslStream}; use protobuf; // Connect const SSL_HANDSHAKE_RETRIES: u8 = 3; #[derive(Debug)] pub enum ConnectionError { E...
//fn read_message(&self) -> Result<protobuf::core::Message, ReadError> { //} }
random_line_split
connection.rs
use proto; use byteorder::{BigEndian, WriteBytesExt}; use std; use std::net::{IpAddr, TcpStream}; use std::sync::Mutex; use openssl; use openssl::ssl::{HandshakeError, SslContext, SslMethod, SslStream}; use protobuf; // Connect const SSL_HANDSHAKE_RETRIES: u8 = 3; #[derive(Debug)] pub enum ConnectionError { E...
(e: std::io::Error) -> Self { ConnectionError::TcpStream(e) } } #[derive(Debug)] pub enum SendError { MessageTooLarge(&'static str), Ssl(openssl::ssl::Error) } // TODO: this should impl error, display impl From<openssl::ssl::Error> for SendError { fn from(e: openssl::ssl::Error) -> Self { ...
from
identifier_name
symbol.rs
use clingo::*; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; fn main() { // create a number, identifier (function without arguments), and a function symbol let number_symbol = Symbol::create_number(42); let identifier_symbol = Symbol::create_id("x", true).unwrap(); let ...
println!(" to {}", symbol.to_string().unwrap()); } // less than comparison print!("{} is ", symbols[0].to_string().unwrap()); if symbols[0] < symbols[1] { print!("less"); } else { print!("not less"); } println!(" than {}", symbols[1].to_string().unwrap()); }
{ print!("not equal"); }
conditional_block
symbol.rs
use clingo::*; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; fn main() { // create a number, identifier (function without arguments), and a function symbol let number_symbol = Symbol::create_number(42); let identifier_symbol = Symbol::create_id("x", true).unwrap(); let ...
"the hash of {} is {}", symbol.to_string().unwrap(), hasher.finish() ); } // retrieve argument symbols of a symbol let symbols2 = function_symbol.arguments().unwrap(); // equal to comparison for symbol in symbols2 { print!("{} is ", symbols[0].to...
// print the symbols along with their hash values let mut hasher = DefaultHasher::new(); for symbol in &symbols { symbol.hash(&mut hasher); println!(
random_line_split
symbol.rs
use clingo::*; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; fn
() { // create a number, identifier (function without arguments), and a function symbol let number_symbol = Symbol::create_number(42); let identifier_symbol = Symbol::create_id("x", true).unwrap(); let mut symbols = vec![number_symbol, identifier_symbol]; let function_symbol = Symbol::create_functi...
main
identifier_name
symbol.rs
use clingo::*; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; fn main()
// retrieve argument symbols of a symbol let symbols2 = function_symbol.arguments().unwrap(); // equal to comparison for symbol in symbols2 { print!("{} is ", symbols[0].to_string().unwrap()); if symbols[0] == symbol { print!("equal"); } else { print!("no...
{ // create a number, identifier (function without arguments), and a function symbol let number_symbol = Symbol::create_number(42); let identifier_symbol = Symbol::create_id("x", true).unwrap(); let mut symbols = vec![number_symbol, identifier_symbol]; let function_symbol = Symbol::create_function(...
identifier_body
unboxed-closure-sugar-not-used-on-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T>(x: &T) where T: Fn<(),()> { //~^ ERROR angle-bracket notation is not stable when used with the `Fn` family } fn main() { }
bar2
identifier_name
unboxed-closure-sugar-not-used-on-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// Test that the `Fn` traits require `()` form without a feature gate. fn bar1(x: &Fn<(),()>) { //~^ ERROR angle-bracket notation is not stable when used with the `Fn` family } fn bar2<T>(x: &T) where T: Fn<(),()> { //~^ ERROR angle-bracket notation is not stable when used with the `Fn` family } fn main() { ...
random_line_split
unboxed-closure-sugar-not-used-on-fn.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { }
{ //~^ ERROR angle-bracket notation is not stable when used with the `Fn` family }
identifier_body
tokenize.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
{ in_char_run: bool, } impl TokenPrinter { fn is_char(&mut self, is_char: bool) { match (self.in_char_run, is_char) { (false, true ) => print!("CHAR : \""), (true, false) => println!("\""), _ => (), } self.in_char_run = is_char; } fn do_cha...
TokenPrinter
identifier_name
tokenize.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
println!(">"); } ParseError(err) => { self.is_char(false); println!("ERROR: {:s}", err); } _ => { self.is_char(false); println!("OTHER: {}", token); } } } } fn main()...
{ print!(" \x1b[31m/\x1b[0m"); }
conditional_block
tokenize.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
ParseError(err) => { self.is_char(false); println!("ERROR: {:s}", err); } _ => { self.is_char(false); println!("OTHER: {}", token); } } } } fn main() { let mut sink = TokenPrinter { i...
random_line_split
master.rs
//! The master module provides the Master struct which instructs Workers which //! portions of the image they should render and collects their results to combine //! into the final image. use std::path::PathBuf; use std::io::prelude::*; use std::collections::HashMap; use std::net::ToSocketAddrs; use std::iter; use std...
} /// Buffer for collecting results from a worker asynchronously. The buffer is filled /// as we get readable events from the workers until it reaches the expected size. /// After this the Frame is decoded and accumulated in the appropriate `DistributedFrame` #[derive(Clone, Debug)] struct WorkerBuffer { pub buf:...
{ DistributedFrame::InProgress { num_reporting: 0, render: Image::new(img_dim), first_tile_recv: SystemTime::now(), } }
identifier_body
master.rs
//! The master module provides the Master struct which instructs Workers which //! portions of the image they should render and collects their results to combine //! into the final image. use std::path::PathBuf; use std::io::prelude::*; use std::collections::HashMap; use std::net::ToSocketAddrs; use std::iter; use std...
for (i, host) in workers.iter().enumerate() { let addr = (&host[..], worker::PORT).to_socket_addrs().unwrap().next().unwrap(); match TcpStream::connect(&addr) { Ok(stream) => { // Each worker is identified in the event loop by their index in the vec ...
random_line_split
master.rs
//! The master module provides the Master struct which instructs Workers which //! portions of the image they should render and collects their results to combine //! into the final image. use std::path::PathBuf; use std::io::prelude::*; use std::collections::HashMap; use std::net::ToSocketAddrs; use std::iter; use std...
(img_dim: (usize, usize)) -> DistributedFrame { DistributedFrame::InProgress { num_reporting: 0, render: Image::new(img_dim), first_tile_recv: SystemTime::now(), } } } /// Buffer for collecting results from a worker asynchronously. The buffer is filled /// as we ...
start
identifier_name
command.rs
// Copyright (C) 2018 Pietro Albini // // 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 option) any later version. // // This program is distrib...
{ child: process::Child, stdout: BufReader<process::ChildStdout>, stderr: BufReader<process::ChildStderr>, } impl Command { pub fn new(binary: &str, args: &[&str]) -> Result<Self> { let mut child = process::Command::new(binaries_path()?.join(binary)) .args(args) .stdout(p...
Command
identifier_name
command.rs
// Copyright (C) 2018 Pietro Albini // // 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 option) any later version. // // This program is distrib...
impl FisherCommand { pub fn new(config: &Config) -> Result<Self> { Ok(FisherCommand { inner: Command::new("fisher", &[ config.save()?.to_str().unwrap(), ])?, }) } pub fn server_addr(&mut self) -> Result<SocketAddr> { let line = self.capture_l...
}
random_line_split
sleeper_list.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 ...
else { None } } } } } impl Clone for SleeperList { fn clone(&self) -> SleeperList { SleeperList { state: self.state.clone() } } }
{ // NB: count is also protected by the lock (*state).count -= 1; Some((*state).stack.pop()) }
conditional_block
sleeper_list.rs
// Copyright 2013 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. //! Maintains a ...
// http://rust-lang.org/COPYRIGHT.
random_line_split
sleeper_list.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 fn push(&mut self, handle: SchedHandle) { let handle = Cell::new(handle); unsafe { let state = self.state.get(); do (*state).lock.lock { (*state).count += 1; (*state).stack.push(handle.take()); } } } pub fn po...
{ SleeperList { state: UnsafeArc::new(State { count: 0, stack: ~[], lock: LittleLock::new() }) } }
identifier_body
sleeper_list.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 ...
() -> SleeperList { SleeperList { state: UnsafeArc::new(State { count: 0, stack: ~[], lock: LittleLock::new() }) } } pub fn push(&mut self, handle: SchedHandle) { let handle = Cell::new(handle); unsafe { ...
new
identifier_name
task-perf-alloc-unwind.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 ...
(repeat: int, depth: int) { for _ in range(0, repeat) { let dur = Duration::span(|| { task::try(proc() { recurse_or_panic(depth, None) }); }); println!("iter: {}", dur); } } type nillist = List<()>; // Filled with things that have to be unwound ...
run
identifier_name
task-perf-alloc-unwind.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. //
// <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. #![feature(unsafe_destructor)] use std::os; use std::task; use std::time::Duration; #[deriving(Clone)] enum List<T> { Nil, Cons(T, Box<List<T>>) } ...
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
random_line_split
task-perf-alloc-unwind.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 { let depth = depth - 1; let st = match st { None => { State { unique: box Nil, vec: vec!(box Nil), res: r(box Nil) } } Some(st) => { let mut v = st.vec....
{ panic!(); }
conditional_block
lib.rs
//! # url_open //! A simple crate to open URLs in the default web browser. //! //! ### Usage //! //! ```no_run //! extern crate url; //! extern crate url_open; //! //! use url::Url; //! use url_open::UrlOpen; //! //! fn main() { //! Url::parse("https://github.com/overdrivenpotato/url_open").unwrap().open(); //! } /...
#[cfg(target_os = "linux")] pub fn open(url: &Url) { let _ = std::process::Command::new("xdg-open").arg(url.to_string()).output(); }
{ let _ = std::process::Command::new("open").arg(url.to_string()).output(); }
identifier_body
lib.rs
//! # url_open //! A simple crate to open URLs in the default web browser. //! //! ### Usage //! //! ```no_run //! extern crate url; //! extern crate url_open; //! //! use url::Url; //! use url_open::UrlOpen; //! //! fn main() { //! Url::parse("https://github.com/overdrivenpotato/url_open").unwrap().open(); //! } /...
(url: &Url) { let _ = std::process::Command::new("xdg-open").arg(url.to_string()).output(); }
open
identifier_name
lib.rs
//! # url_open //! A simple crate to open URLs in the default web browser. //! //! ### Usage //! //! ```no_run //! extern crate url; //! extern crate url_open; //! //! use url::Url; //! use url_open::UrlOpen; //! //! fn main() { //! Url::parse("https://github.com/overdrivenpotato/url_open").unwrap().open(); //! } /...
impl UrlOpen for Url { fn open(&self) { open(self); } } #[cfg(target_os = "windows")] pub fn open(url: &Url) { extern crate shell32; extern crate winapi; use std::ffi::CString; use std::ptr; unsafe { shell32::ShellExecuteA(ptr::null_mut(), C...
/// Convenience method to open URLs pub trait UrlOpen { fn open(&self); }
random_line_split
map.rs
use engine::Tile; use util::FromChar; use util::units::{Point, Size}; use std::path::Path; use std::fs::File; use std::io::Read; /// A map. pub struct Map { pub tiles: Vec<Vec<Tile>>, pub size: Size, pub starting_position: Point, } impl Map { /// Creates a new map from a string. pub fn from_strin...
pub fn is_walkable(&self, loc: Point) -> bool { self.at(loc).is_walkable() } pub fn set_tile(&mut self, loc: Point, tile: Tile) { self.tiles[loc.y as usize][loc.x as usize] = tile; } pub fn height(&self) -> i32 { self.tiles.len() as i32 } pub fn width(&self) -> i...
{ self.tiles[loc.y as usize][loc.x as usize] }
identifier_body
map.rs
use engine::Tile; use util::FromChar; use util::units::{Point, Size}; use std::path::Path; use std::fs::File; use std::io::Read; /// A map. pub struct Map { pub tiles: Vec<Vec<Tile>>, pub size: Size, pub starting_position: Point, } impl Map { /// Creates a new map from a string. pub fn from_strin...
pub fn from_file<T>(path: T) -> Map where T: AsRef<Path>, { let mut level_file = File::open(path).ok().expect("Could not find level file"); let mut level_string = String::new(); level_file .read_to_string(&mut level_string) .ok() .expect("Co...
size: size, starting_position: starting_position, } }
random_line_split
map.rs
use engine::Tile; use util::FromChar; use util::units::{Point, Size}; use std::path::Path; use std::fs::File; use std::io::Read; /// A map. pub struct Map { pub tiles: Vec<Vec<Tile>>, pub size: Size, pub starting_position: Point, } impl Map { /// Creates a new map from a string. pub fn from_strin...
let tiles: Vec<Vec<Tile>> = lines .iter() .map(|l| l.chars().map(|c| Tile::from_char(c)).collect()) .collect(); let mut starting_position = None; for (y, row_vec) in lines.iter().enumerate() { for (x, tile) in row_vec.chars().enumerate() { ...
{ panic!("Different length lines in level string") }
conditional_block
map.rs
use engine::Tile; use util::FromChar; use util::units::{Point, Size}; use std::path::Path; use std::fs::File; use std::io::Read; /// A map. pub struct Map { pub tiles: Vec<Vec<Tile>>, pub size: Size, pub starting_position: Point, } impl Map { /// Creates a new map from a string. pub fn from_strin...
(&self) -> i32 { self.tiles[0].len() as i32 } }
width
identifier_name
mod.rs
pub use self::cargo_clean::{clean, CleanOptions}; pub use self::cargo_compile::{compile, compile_pkg, resolve_dependencies, CompileOptions};
pub use self::cargo_rustc::{Context, LayoutProxy}; pub use self::cargo_rustc::{BuildOutput, BuildConfig, TargetConfig}; pub use self::cargo_rustc::{CommandType, CommandPrototype, ExecEngine, ProcessEngine}; pub use self::cargo_run::run; pub use self::cargo_install::{install, install_list, uninstall}; pub use self::carg...
pub use self::cargo_compile::{CompileFilter, CompileMode}; pub use self::cargo_read_manifest::{read_manifest,read_package,read_packages}; pub use self::cargo_rustc::{compile_targets, Compilation, Layout, Kind, Unit};
random_line_split
mod.rs
mod square; use gameboy::apu::square::SquareChannel; const AUDIO_BUFFER_LENGTH: usize = 8192; pub struct APU { audio_buffer: Box<[f32]>, buffer_index: usize, counter: u32, /* Increments at 4.2 Mhz */ timer: u32, /* Increments at 512 Hz*/ sample_rate: u32, /* Sample per second (Hz) */ square_1: SquareChannel, ...
let base_time = (self.timer as f32) / 512.0_f32; let sample_count = self.sample_rate / 512; /* 1 sound frame is 1/512 second */ let samples_generated = self.square_2.sample( &mut self.audio_buffer[self.buffer_index.. AUDIO_BUFFER_LENGTH], self.sample_rate, sample_count, base_time, 1.0_f32 ...
random_line_split
mod.rs
mod square; use gameboy::apu::square::SquareChannel; const AUDIO_BUFFER_LENGTH: usize = 8192; pub struct APU { audio_buffer: Box<[f32]>, buffer_index: usize, counter: u32, /* Increments at 4.2 Mhz */ timer: u32, /* Increments at 512 Hz*/ sample_rate: u32, /* Sample per second (Hz) */ square_1: SquareChannel, ...
(&mut self, double_speed_mode: bool, div: u16, last_div: u16) { /* From what i understand the sound clock is actually the cpu clock divided by 8192 (16,384 in double speed mode) which equals ~512 Hz. http://gbdev.gg8.se/wiki/articles/Timer_Obscure_Behaviour */ if double_speed_mode { self.counter = se...
emulate_hardware
identifier_name
mod.rs
mod square; use gameboy::apu::square::SquareChannel; const AUDIO_BUFFER_LENGTH: usize = 8192; pub struct APU { audio_buffer: Box<[f32]>, buffer_index: usize, counter: u32, /* Increments at 4.2 Mhz */ timer: u32, /* Increments at 512 Hz*/ sample_rate: u32, /* Sample per second (Hz) */ square_1: SquareChannel, ...
let samples_generated = self.square_2.sample( &mut self.audio_buffer[self.buffer_index.. AUDIO_BUFFER_LENGTH], self.sample_rate, sample_count, base_time, 1.0_f32 ); self.buffer_index += samples_generated; } /* Falling edge detector for 512 Hz timer driven by divider register */ if (...
{ /* From what i understand the sound clock is actually the cpu clock divided by 8192 (16,384 in double speed mode) which equals ~512 Hz. http://gbdev.gg8.se/wiki/articles/Timer_Obscure_Behaviour */ if double_speed_mode { self.counter = self.counter.wrapping_add(2); } else { self.counter = sel...
identifier_body
issue-23433.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 ...
() { let mut a = [0u8; 5]; let b: Option<Unique<[u8]>> = unsafe { Some(Unique::new(&mut a)) }; match b { Some(_) => println!("Got `Some`"), None => panic!("Unexpected `None`"), } }
main
identifier_name
issue-23433.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 ...
{ let mut a = [0u8; 5]; let b: Option<Unique<[u8]>> = unsafe { Some(Unique::new(&mut a)) }; match b { Some(_) => println!("Got `Some`"), None => panic!("Unexpected `None`"), } }
identifier_body
issue-23433.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 ...
None => panic!("Unexpected `None`"), } }
match b { Some(_) => println!("Got `Some`"),
random_line_split
extra_assertions.rs
//! Macros for defining extra assertions that should only be checked in testing //! and/or CI when the `testing_only_extra_assertions` feature is enabled. /// Simple macro that forwards to assert! when using /// testing_only_extra_assertions. #[macro_export] macro_rules! extra_assert { ( $cond:expr ) => { ...
( $lhs:expr, $rhs:expr, $( $arg:tt )+ ) => { if cfg!(feature = "testing_only_extra_assertions") { assert!($lhs, $rhs, $( $arg )* ); } }; }
( $lhs:expr , $rhs:expr ) => { if cfg!(feature = "testing_only_extra_assertions") { assert_eq!($lhs, $rhs); } };
random_line_split
backtrace.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 ...
() { fail!() } #[inline(never)] fn double() { (|| { fail!("once"); }).finally(|| { fail!("twice"); }) } fn runtest(me: &str) { let mut env = os::env().move_iter() .map(|(ref k, ref v)| { (k.to_string(), v.to_string()) ...
foo
identifier_name
backtrace.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 ...
None => {} } env.push(("RUST_BACKTRACE".to_string(), "1".to_string())); // Make sure that the stack trace is printed let mut p = Command::new(me).arg("fail").env(env.as_slice()).spawn().unwrap(); let out = p.wait_with_output().unwrap(); assert!(!out.status.success()); let s = str::f...
(k.to_string(), v.to_string()) }).collect::<Vec<(String,String)>>(); match env.iter() .position(|&(ref s, _)| "RUST_BACKTRACE" == s.as_slice()) { Some(i) => { env.remove(i); }
random_line_split
backtrace.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 runtest(me: &str) { let mut env = os::env().move_iter() .map(|(ref k, ref v)| { (k.to_string(), v.to_string()) }).collect::<Vec<(String,String)>>(); match env.iter() .position(|&(ref s, _)| "RUST_BACKTRACE" == s...
{ (|| { fail!("once"); }).finally(|| { fail!("twice"); }) }
identifier_body
backtrace.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 ...
}
{ runtest(args[0].as_slice()); }
conditional_block
point_bounding_sphere.rs
use na::{Identity, Transform}; use point::PointQuery; use entities::shape::Ball; use entities::bounding_volume::BoundingSphere; use math::{Scalar, Point, Vect}; impl<P, M> PointQuery<P, M> for BoundingSphere<P> where P: Point, M: Transform<P> { #[inline] fn
(&self, m: &M, pt: &P, solid: bool) -> P { let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec()); let proj = Ball::new(self.radius()).project_point(&Identity::new(), &ls_pt, solid); m.transform(&proj) + *self.center().as_vec() } #[inline] fn distance_to_point(&self, m: &M, ...
project_point
identifier_name
point_bounding_sphere.rs
use na::{Identity, Transform}; use point::PointQuery; use entities::shape::Ball; use entities::bounding_volume::BoundingSphere; use math::{Scalar, Point, Vect}; impl<P, M> PointQuery<P, M> for BoundingSphere<P> where P: Point, M: Transform<P> { #[inline] fn project_point(&self, m: &M, pt: &P, sol...
let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec()); Ball::new(self.radius()).contains_point(&Identity::new(), &ls_pt) } }
} #[inline] fn contains_point(&self, m: &M, pt: &P) -> bool {
random_line_split
point_bounding_sphere.rs
use na::{Identity, Transform}; use point::PointQuery; use entities::shape::Ball; use entities::bounding_volume::BoundingSphere; use math::{Scalar, Point, Vect}; impl<P, M> PointQuery<P, M> for BoundingSphere<P> where P: Point, M: Transform<P> { #[inline] fn project_point(&self, m: &M, pt: &P, sol...
}
{ let ls_pt = m.inv_transform(pt) + (-*self.center().as_vec()); Ball::new(self.radius()).contains_point(&Identity::new(), &ls_pt) }
identifier_body
from.rs
header! { #[doc="`From` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.5.1)"] #[doc=""] #[doc="The `From` header field contains an Internet email address for a"] #[doc="human user who controls the requesting user agent. The address ought"] #[doc="to be machine-usable."] ...
#[doc="# Example"] #[doc="```"] #[doc="use hyper::header::{Headers, From};"] #[doc=""] #[doc="let mut headers = Headers::new();"] #[doc="headers.set(From(\"webmaster@example.org\".to_owned()));"] #[doc="```"] // FIXME: Maybe use mailbox? (From, "From") => [String] test_from { ...
#[doc="From = mailbox"] #[doc="mailbox = <mailbox, see [RFC5322], Section 3.4>"] #[doc="```"] #[doc=""]
random_line_split
testcase.rs
#[derive(Debug)] struct I32(i32); #[derive(Debug)] struct I64(i64); // `Self + Rhs = Sum`: Once the types for `Self` and `Rhs` are // determined, `Sum` is known. trait Add<Rhs> { type Sum; // Use `&self` and `&Rhs` so no changes are made to the originals. // The return shouldn't be a reference. fn add...
() { let i = I32(12); let j = I64(9); println!("{:?} + {:?} = {:?}", &i, &i, i.add(&i)); println!("{:?} + {:?} = {:?}", &i, &j, i.add(&j)); println!("{:?} + {:?} = {:?}", &j, &i, j.add(&i)); println!("{:?} + {:?} = {:?}", &j, &j, j.add(&j)); }
main
identifier_name
testcase.rs
#[derive(Debug)] struct I32(i32); #[derive(Debug)] struct I64(i64); // `Self + Rhs = Sum`: Once the types for `Self` and `Rhs` are // determined, `Sum` is known. trait Add<Rhs> { type Sum; // Use `&self` and `&Rhs` so no changes are made to the originals. // The return shouldn't be a reference. fn add...
println!("{:?} + {:?} = {:?}", &i, &j, i.add(&j)); println!("{:?} + {:?} = {:?}", &j, &i, j.add(&i)); println!("{:?} + {:?} = {:?}", &j, &j, j.add(&j)); }
fn main() { let i = I32(12); let j = I64(9); println!("{:?} + {:?} = {:?}", &i, &i, i.add(&i));
random_line_split
testcase.rs
#[derive(Debug)] struct I32(i32); #[derive(Debug)] struct I64(i64); // `Self + Rhs = Sum`: Once the types for `Self` and `Rhs` are // determined, `Sum` is known. trait Add<Rhs> { type Sum; // Use `&self` and `&Rhs` so no changes are made to the originals. // The return shouldn't be a reference. fn add...
} impl Add<I64> for I64 { type Sum = I64; fn add(&self, rhs: &I64) -> Self::Sum { I64(self.0 + rhs.0) } } fn main() { let i = I32(12); let j = I64(9); println!("{:?} + {:?} = {:?}", &i, &i, i.add(&i)); println!("{:?} + {:?} = {:?}", &i, &j, i.add(&j)); println!("{:?} + {:?} = {:?}", &...
{ I64(self.0 + rhs.0 as i64) }
identifier_body
create_state_event_for_key.rs
//! [PUT /_matrix/client/r0/rooms/{roomId}/state/{eventType}/{stateKey}](https://matrix.org/docs/spec/client_server/r0.6.0#put-matrix-client-r0-rooms-roomid-state-eventtype-statekey) use ruma_api::ruma_api; use ruma_events::EventType; use ruma_identifiers::{EventId, RoomId}; use serde_json::value::RawValue as RawJsonV...
/// The state_key for the state to send. Defaults to the empty string. #[ruma_api(path)] pub state_key: String, /// The event's content. The type for this field will be updated in a /// future release, until then you can create a value using /// `serde_json::value::to_ra...
random_line_split
mod.rs
#![cfg(any(target_os = "linux", target_os = "freebsd"))] #![allow(unused_variables, dead_code)] use libc; use api::osmesa::{OsMesaContext, OsMesaCreationError}; use Api; use ContextError; use CreationError; use Event; use GlAttributes; use GlContext; use PixelFormat; use PixelFormatRequirements; use CursorState; use ...
#[inline] fn is_current(&self) -> bool { self.opengl.is_current() } #[inline] fn get_proc_address(&self, addr: &str) -> *const () { self.opengl.get_proc_address(addr) } #[inline] fn swap_buffers(&self) -> Result<(), ContextError> { unsafe { let canv...
random_line_split
mod.rs
#![cfg(any(target_os = "linux", target_os = "freebsd"))] #![allow(unused_variables, dead_code)] use libc; use api::osmesa::{OsMesaContext, OsMesaCreationError}; use Api; use ContextError; use CreationError; use Event; use GlAttributes; use GlContext; use PixelFormat; use PixelFormatRequirements; use CursorState; use ...
#[inline] pub fn get_inner_size(&self) -> Option<(u32, u32)> { Some(self.opengl.get_dimensions()) } #[inline] pub fn get_outer_size(&self) -> Option<(u32, u32)> { self.get_inner_size() } #[inline] pub fn set_inner_size(&self, _x: u32, _y: u32) { unimplemented!...
{ }
identifier_body
mod.rs
#![cfg(any(target_os = "linux", target_os = "freebsd"))] #![allow(unused_variables, dead_code)] use libc; use api::osmesa::{OsMesaContext, OsMesaCreationError}; use Api; use ContextError; use CreationError; use Event; use GlAttributes; use GlContext; use PixelFormat; use PixelFormatRequirements; use CursorState; use ...
() -> MonitorId { MonitorId } impl MonitorId { #[inline] pub fn get_name(&self) -> Option<String> { unimplemented!(); } #[inline] pub fn get_native_identifier(&self) -> ::native_monitor::NativeMonitorId { ::native_monitor::NativeMonitorId::Unavailable } #[inline] p...
get_primary_monitor
identifier_name
mod.rs
#![cfg(any(target_os = "linux", target_os = "freebsd"))] #![allow(unused_variables, dead_code)] use libc; use api::osmesa::{OsMesaContext, OsMesaCreationError}; use Api; use ContextError; use CreationError; use Event; use GlAttributes; use GlContext; use PixelFormat; use PixelFormatRequirements; use CursorState; use ...
Ok(Window { libcaca: libcaca, display: display, opengl: opengl, dither: dither, }) } #[inline] pub fn set_title(&self, title: &str) { } #[inline] pub fn show(&self) { } #[inline] pub fn hide(&self) { } #[in...
{ unsafe { (libcaca.caca_free_display)(display) }; return Err(CreationError::OsError("caca_create_dither failed".to_string())); }
conditional_block
encoding.rs
//! The `Encoding` struct. use binemit::CodeOffset; use isa::constraints::{RecipeConstraints, BranchRange}; use std::fmt; /// Bits needed to encode an instruction as binary machine code. /// /// The encoding consists of two parts, both specific to the target ISA: An encoding *recipe*, and /// encoding *bits*. The rec...
} } /// Code size information for an encoding recipe. /// /// All encoding recipes correspond to an exact instruction size. pub struct RecipeSizing { /// Size in bytes of instructions encoded with this recipe. pub bytes: u8, /// Allowed branch range in this recipe, if any. /// /// All encodin...
{ write!(f, "-") }
conditional_block
encoding.rs
//! The `Encoding` struct. use binemit::CodeOffset; use isa::constraints::{RecipeConstraints, BranchRange}; use std::fmt; /// Bits needed to encode an instruction as binary machine code. /// /// The encoding consists of two parts, both specific to the target ISA: An encoding *recipe*, and /// encoding *bits*. The rec...
(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.encoding.is_legal() { write!( f, "{}#{:02x}", self.recipe_names[self.encoding.recipe()], self.encoding.bits ) } else { write!(f, "-") } ...
fmt
identifier_name
encoding.rs
//! The `Encoding` struct. use binemit::CodeOffset; use isa::constraints::{RecipeConstraints, BranchRange}; use std::fmt; /// Bits needed to encode an instruction as binary machine code. /// /// The encoding consists of two parts, both specific to the target ISA: An encoding *recipe*, and /// encoding *bits*. The rec...
pub fn operand_constraints(&self, enc: Encoding) -> Option<&'static RecipeConstraints> { self.constraints.get(enc.recipe()) } /// Create an object that can display an ISA-dependent encoding properly. pub fn display(&self, enc: Encoding) -> DisplayEncoding { DisplayEncoding { ...
impl EncInfo { /// Get the value operand constraints for `enc` if it is a legal encoding.
random_line_split
graph.rs
// Copyright (c) 2017 Jason White
// in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright noti...
// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal
random_line_split
graph.rs
// Copyright (c) 2017 Jason White // // 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 use, copy, modify, merge, publish, d...
else { let mut stdout = io::stdout(); build_graph.graphviz(&mut stdout.lock())?; stdout.flush() // Flush to catch write errors } .context("Failed writing GraphViz DOT file")?; Ok(()) } }
{ let mut stream = io::BufWriter::new(fs::File::create(&output).with_context( |_| format!("Failed creating '{}'", output.display()), )?); build_graph.graphviz(&mut stream)?; stream.flush() // Flush to catch write errors }
conditional_block
graph.rs
// Copyright (c) 2017 Jason White // // 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 use, copy, modify, merge, publish, d...
{ /// Path to the build rules. If not specified, finds "button.json" in the /// current directory or parent directories. #[structopt(long = "rules", short = "r", parse(from_os_str))] rules: Option<PathBuf>, /// Path to the output file. If not specified, writes to standard output. #[structopt(l...
Graph
identifier_name
lib.rs
// A rust wrapper to a small subset of TestU01 // (http://simul.iro.umontreal.ca/testu01/tu01.html). // Copyright (C) 2015 Loïc Damien // // 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, eith...
use std::sync::Mutex; lazy_static! { /// Lot of TestU01 is inherently non thread-safe, updating/reading global variables without /// synchronization. This lock is here to protect access to all TestU01 global variables. static ref GLOBAL_LOCK: Mutex<()> = Mutex::new(()); } pub mod decorators; pub mod batte...
random_line_split
std_qsearch.rs
//! Implements `StdQsearch` and `StdQsearchResult`. use std::cell::UnsafeCell; use std::marker::PhantomData; use uci::{SetOption, OptionDescription}; use board::*; use value::*; use depth::*; use moves::*; use evaluator::Evaluator; use qsearch::{Qsearch, QsearchParams, QsearchResult}; use move_generator::MoveGenerator...
} /// Implements the `Qsearch` trait. /// /// Performs classical quiescence search with stand pat, delta /// pruning, static exchange evaluation, check evasions, limited /// checks and recaptures. pub struct StdQsearch<T: MoveGenerator> { phantom: PhantomData<T>, } impl<T: MoveGenerator> Qsearch for StdQsearch<...
{ self.searched_nodes }
identifier_body
std_qsearch.rs
//! Implements `StdQsearch` and `StdQsearchResult`. use std::cell::UnsafeCell; use std::marker::PhantomData; use uci::{SetOption, OptionDescription}; use board::*; use value::*; use depth::*; use moves::*; use evaluator::Evaluator; use qsearch::{Qsearch, QsearchParams, QsearchResult}; use move_generator::MoveGenerator...
// Try the move. if position.do_move(m).is_some() { // If the move does not give check, ensure that // the immediate material gain from the move is // big enough. if!position.is_check() { let material_gain = if move_type == MOVE_PROMOTION...
{ match position.evaluate_move(m) { // A losing move -- do not try it. x if x < 0 => continue 'trymoves, // An even exchange -- try it only during the first few plys. 0 if ply >= 2 && captured_piece < PIECE_NONE => continue 'trymoves, ...
conditional_block
std_qsearch.rs
//! Implements `StdQsearch` and `StdQsearchResult`. use std::cell::UnsafeCell; use std::marker::PhantomData; use uci::{SetOption, OptionDescription}; use board::*; use value::*; use depth::*; use moves::*; use evaluator::Evaluator; use qsearch::{Qsearch, QsearchParams, QsearchResult}; use move_generator::MoveGenerator...
let mut p = P::from_board(board).ok().unwrap(); assert!(qsearch(&mut p, -1000, 1000, VALUE_UNKNOWN, 0, 0, &mut s, &mut 0) > 225 - d); let fen = "8/8/8/8/5pkp/6P1/5P1P/6K1 b - - 0 1"; let board = Board::from_fen(fen).ok().unwrap(); let mut p = P::from_board(board).ok().unwrap(); ...
let fen = "8/8/8/8/6k1/6P1/8/5bK1 b - - 0 1"; let board = Board::from_fen(fen).ok().unwrap();
random_line_split
std_qsearch.rs
//! Implements `StdQsearch` and `StdQsearchResult`. use std::cell::UnsafeCell; use std::marker::PhantomData; use uci::{SetOption, OptionDescription}; use board::*; use value::*; use depth::*; use moves::*; use evaluator::Evaluator; use qsearch::{Qsearch, QsearchParams, QsearchResult}; use move_generator::MoveGenerator...
(name: &str, value: &str) { T::set_option(name, value) } } /// A classical recursive quiescence search implementation. fn qsearch<T: MoveGenerator>(position: &mut T, mut lower_bound: Value, // alpha upper_bound: Value, // beta ...
set_option
identifier_name
polygon.rs
use image::{GenericImage, ImageBuffer}; use definitions::Image; use std::cmp::{min, max}; use std::f32; use std::i32; use drawing::draw_if_in_bounds; use drawing::line::draw_line_segment_mut; /// A 2D point. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Point<T: Copy + PartialEq + Eq> { x: T, y: T, }...
} intersections.sort(); let mut i = 0; loop { // Handle points where multiple lines intersect while i + 1 < intersections.len() && intersections[i] == intersections[i + 1] { i += 1; } if i >= intersections.len() { ...
{ // Need to handle horizontal lines specially if p0.y == p1.y { intersections.push(p0.x); intersections.push(p1.x); } else { let fraction = (y - p0.y) as f32 / (p1.y - p0.y) as f32; let inter...
conditional_block
polygon.rs
use image::{GenericImage, ImageBuffer}; use definitions::Image; use std::cmp::{min, max}; use std::f32; use std::i32; use drawing::draw_if_in_bounds; use drawing::line::draw_line_segment_mut; /// A 2D point. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Point<T: Copy + PartialEq + Eq> { x: T, y: T, }...
pub fn new(x: T, y: T) -> Point<T> { Point::<T> { x: x, y: y } } } /// Draws as much of a filled convex polygon as lies within image bounds. The provided /// list of points should be an open path, i.e. the first and last points must not be equal. /// An implicit edge is added from the last to the first...
/// Construct a point at (x, y).
random_line_split
polygon.rs
use image::{GenericImage, ImageBuffer}; use definitions::Image; use std::cmp::{min, max}; use std::f32; use std::i32; use drawing::draw_if_in_bounds; use drawing::line::draw_line_segment_mut; /// A 2D point. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Point<T: Copy + PartialEq + Eq> { x: T, y: T, }...
} /// Draws as much of a filled convex polygon as lies within image bounds. The provided /// list of points should be an open path, i.e. the first and last points must not be equal. /// An implicit edge is added from the last to the first point in the slice. /// /// Does not validate that input is convex. pub fn draw...
{ Point::<T> { x: x, y: y } }
identifier_body
polygon.rs
use image::{GenericImage, ImageBuffer}; use definitions::Image; use std::cmp::{min, max}; use std::f32; use std::i32; use drawing::draw_if_in_bounds; use drawing::line::draw_line_segment_mut; /// A 2D point. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Point<T: Copy + PartialEq + Eq> { x: T, y: T, }...
<I>(image: &I, poly: &[Point<i32>], color: I::Pixel) -> Image<I::Pixel> where I: GenericImage, I::Pixel:'static, { let mut out = ImageBuffer::new(image.width(), image.height()); out.copy_from(image, 0, 0); draw_convex_polygon_mut(&mut out, poly, color); out } /// Draws as much of a filled conve...
draw_convex_polygon
identifier_name
access_control_allow_origin.rs
use std::fmt::{self, Display}; use header::{Header, HeaderFormat}; /// The `Access-Control-Allow-Origin` response header, /// part of [CORS](http://www.w3.org/TR/cors/#access-control-allow-origin-response-header) /// /// The `Access-Control-Allow-Origin` header indicates whether a resource /// can be shared based by ...
/// Allow all origins Any, /// A hidden origin Null, /// Allow one particular origin Value(String), } impl Header for AccessControlAllowOrigin { fn header_name() -> &'static str { "Access-Control-Allow-Origin" } fn parse_header(raw: &[Vec<u8>]) -> ::Result<AccessControlAllo...
/// AccessControlAllowOrigin::Value("http://hyper.rs".to_owned()) /// ); /// ``` #[derive(Clone, PartialEq, Debug)] pub enum AccessControlAllowOrigin {
random_line_split
access_control_allow_origin.rs
use std::fmt::{self, Display}; use header::{Header, HeaderFormat}; /// The `Access-Control-Allow-Origin` response header, /// part of [CORS](http://www.w3.org/TR/cors/#access-control-allow-origin-response-header) /// /// The `Access-Control-Allow-Origin` header indicates whether a resource /// can be shared based by ...
(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { self.fmt_header(f) } } #[cfg(test)] mod test_access_control_allow_orgin { use header::*; use super::AccessControlAllowOrigin as HeaderField; test_header!(test1, vec![b"null"]); test_header!(test2, vec![b"*"]); test_header!(t...
fmt
identifier_name
uppercase_test.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<5485f969d2c4ec061b42a61e18f80eed>> */ mod uppercase; use uppercase::transform_fixture; use fixture_tes...
{ let input = include_str!("uppercase/fixtures/world.txt"); let expected = include_str!("uppercase/fixtures/world.expected"); test_fixture(transform_fixture, "world.txt", "uppercase/fixtures/world.expected", input, expected); }
identifier_body
uppercase_test.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<5485f969d2c4ec061b42a61e18f80eed>> */ mod uppercase; use uppercase::transform_fixture; use fixture_tes...
let expected = include_str!("uppercase/fixtures/hello.expected"); test_fixture(transform_fixture, "hello.txt", "uppercase/fixtures/hello.expected", input, expected); } #[test] fn world() { let input = include_str!("uppercase/fixtures/world.txt"); let expected = include_str!("uppercase/fixtures/world.ex...
#[test] fn hello() { let input = include_str!("uppercase/fixtures/hello.txt");
random_line_split
uppercase_test.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<5485f969d2c4ec061b42a61e18f80eed>> */ mod uppercase; use uppercase::transform_fixture; use fixture_tes...
() { let input = include_str!("uppercase/fixtures/world.txt"); let expected = include_str!("uppercase/fixtures/world.expected"); test_fixture(transform_fixture, "world.txt", "uppercase/fixtures/world.expected", input, expected); }
world
identifier_name
slice-panic-1.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 foo() { let x: &[_] = &[Foo, Foo]; &x[3..4]; } fn main() { let _ = thread::spawn(move|| foo()).join(); unsafe { assert!(DTOR_COUNT == 2); } }
{ unsafe { DTOR_COUNT += 1; } }
identifier_body
slice-panic-1.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x: &[_] = &[Foo, Foo]; &x[3..4]; } fn main() { let _ = thread::spawn(move|| foo()).join(); unsafe { assert!(DTOR_COUNT == 2); } }
foo
identifier_name
slice-panic-1.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 main() { let _ = thread::spawn(move|| foo()).join(); unsafe { assert!(DTOR_COUNT == 2); } }
random_line_split
main.rs
extern mod actor; extern mod std; use actor::actor::{Actor, SurviveOrDie, Survive, Die}; use actor::system::{System}; use std::comm::{SharedChan}; enum PingPongMsg { Ping, Pong, } struct PingPong { counter: uint, master: SharedChan<bool>, } impl <C: GenericChan<PingPongMsg>> Actor<PingPongMsg, PingPongMsg,...
() { let mut system = System::new(); let (master_port, master_chan): (Port<bool>, Chan<bool>) = stream(); let master_chan = SharedChan::new(master_chan); let (port1, chan1): (Port<PingPongMsg>, Chan<PingPongMsg>) = stream(); let (port2, chan2): (Port<PingPongMsg>, Chan<PingPongMsg>) = stream(); ...
main
identifier_name
main.rs
extern mod actor; extern mod std; use actor::actor::{Actor, SurviveOrDie, Survive, Die}; use actor::system::{System}; use std::comm::{SharedChan}; enum PingPongMsg { Ping, Pong, } struct PingPong { counter: uint, master: SharedChan<bool>, } impl <C: GenericChan<PingPongMsg>> Actor<PingPongMsg, PingPongMsg,...
fn main() { let mut system = System::new(); let (master_port, master_chan): (Port<bool>, Chan<bool>) = stream(); let master_chan = SharedChan::new(master_chan); let (port1, chan1): (Port<PingPongMsg>, Chan<PingPongMsg>) = stream(); let (port2, chan2): (Port<PingPongMsg>, Chan<PingPongMsg>) = s...
{ let (counter, master) = args; PingPong{counter: counter, master: master,} }
identifier_body
main.rs
extern mod actor; extern mod std; use actor::actor::{Actor, SurviveOrDie, Survive, Die}; use actor::system::{System}; use std::comm::{SharedChan}; enum PingPongMsg { Ping, Pong, } struct PingPong { counter: uint, master: SharedChan<bool>, } impl <C: GenericChan<PingPongMsg>> Actor<PingPongMsg, PingPongMsg,...
assert_eq!(true, master_port.recv()); }
system.add_actor_from_port_and_chan(port2, chan1, (10u, master_chan.clone()), new_pingpong); // Both actors must terminate assert_eq!(true , master_port.recv());
random_line_split
mission_select.rs
use voodoo::window::{Point, Window}; use game_state::{UiState, ModelView}; const TITLE: [&'static str; 6] = [ "██████╗ ███████╗ ██╗██╗ ██╗ █████╗ ██████╗██╗ ██╗", "██╔══██╗██╔════╝ ██╔╝██║ ██║██╔══██╗██╔════╝██║ ██╔╝", "█████╔╝█████╗ ██╔╝ ███████║███████║██║ █████╔╝", "██╔══██╗██╔══╝ ...
::new(33, 15), "PRESS Q TO QUIT"); mission_state.window.refresh(compositor); }
identifier_body
mission_select.rs
use voodoo::window::{Point, Window}; use game_state::{UiState, ModelView}; const TITLE: [&'static str; 6] = [ "██████╗ ███████╗ ██╗██╗ ██╗ █████╗ ██████╗██╗ ██╗", "██╔══██╗██╔════╝ ██╔╝██║ ██║██╔══██╗██╔════╝██║ ██╔╝", "█████╔╝█████╗ ██╔╝ ███████║███████║██║ █████╔╝", "██╔══██╗██╔══╝ ...
compositor: &mut ::voodoo::compositor::Compositor, _mv: &mut ModelView) { for (offset, line) in TITLE.iter().enumerate() { mission_state.window.print_at(Point::new(13, 6 + offset as u16), *line); } mission_state.window.print_at(Point::new(30, 14), "PRESS ANY KEY TO BEGIN"); mission_state.window....
e,
identifier_name
mission_select.rs
use voodoo::window::{Point, Window}; use game_state::{UiState, ModelView}; const TITLE: [&'static str; 6] = [ "██████╗ ███████╗ ██╗██╗ ██╗ █████╗ ██████╗██╗ ██╗", "██╔══██╗██╔════╝ ██╔╝██║ ██║██╔══██╗██╔════╝██║ ██╔╝", "█████╔╝█████╗ ██╔╝ ███████║███████║██║ █████╔╝", "██╔══██╗██╔══╝ ...
pub enum Transition { Ui(UiState), Level(usize), } pub struct State { window: Window, } impl State { pub fn new(window: Window) -> State { State { window: window, } } } impl ::std::fmt::Debug for State { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::...
pub enum UiEvent { KeyPressed, Tick, }
random_line_split
io.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self) { // Gee, seeing how we're testing the fs module I sure hope that we // at least implement this correctly! let TempDir(ref p) = *self; fs::remove_dir_all(p).unwrap(); } } pub fn tmpdir() -> TempDir { let p = env::temp_dir(); le...
drop
identifier_name
io.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
#[cfg(test)] #[allow(dead_code)] // not used on emscripten pub mod test { use path::{Path, PathBuf}; use env; use rand::{self, RngCore}; use fs; pub struct TempDir(PathBuf); impl TempDir { pub fn join(&self, path: &str) -> PathBuf { let TempDir(ref p) = *self; ...
// <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. pub const DEFAULT_BUF_SIZE: usize = 8 * 1024;
random_line_split
io.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 ...
} impl Drop for TempDir { fn drop(&mut self) { // Gee, seeing how we're testing the fs module I sure hope that we // at least implement this correctly! let TempDir(ref p) = *self; fs::remove_dir_all(p).unwrap(); } } pub fn tmpdir() -> Te...
{ let TempDir(ref p) = *self; p }
identifier_body
debug.rs
//! Tests for our own Debug implementation. //! //! The tests check against expected output. This may be a bit fragile, but it is likely OK for //! actual use. use prost::alloc::{format, string::String}; // Borrow some types from other places. #[cfg(feature = "std")] use crate::message_encoding::Basic; use crate::mes...
} */ #[derive(Clone, PartialEq, prost::Oneof)] pub enum OneofWithEnum { #[prost(int32, tag = "8")] Int(i32), #[prost(string, tag = "9")] String(String), #[prost(enumeration = "BasicEnumeration", tag = "10")] Enumeration(i32), } #[derive(Clone, PartialEq, prost::Message)] struct MessageWithOneo...
random_line_split
debug.rs
//! Tests for our own Debug implementation. //! //! The tests check against expected output. This may be a bit fragile, but it is likely OK for //! actual use. use prost::alloc::{format, string::String}; // Borrow some types from other places. #[cfg(feature = "std")] use crate::message_encoding::Basic; use crate::mes...
{ #[prost(oneof = "OneofWithEnum", tags = "8, 9, 10")] of: Option<OneofWithEnum>, } /// Enumerations inside oneofs #[test] fn oneof_with_enum() { let msg = MessageWithOneof { of: Some(OneofWithEnum::Enumeration(BasicEnumeration::TWO as i32)), }; assert_eq!( format!("{:?}", msg), ...
MessageWithOneof
identifier_name
iter.rs
// Copyright (c) 2016, ilammy // // Licensed under MIT license (see LICENSE file in the root directory). // This file may be copied, distributed, and modified only in accordance // with the terms specified by this license. //! Iterator utilities. use std::iter::Iterator; /// Non-short-circuiting version of `Zip`. Se...
} } /// Returns an iterator which simulataneously walks over two other iterators until _both_ of /// them are exhausted. It is similar to `zip()` method of `Iterator`, but it does not stop /// when one of the iterators in exhausted. /// /// Example: /// ``` /// assert_eq!(longest_zip(&[1, 2, 3], &[5, 6]).collect:...
{ return None; }
conditional_block
iter.rs
// Copyright (c) 2016, ilammy // // Licensed under MIT license (see LICENSE file in the root directory). // This file may be copied, distributed, and modified only in accordance // with the terms specified by this license. //! Iterator utilities. use std::iter::Iterator; /// Non-short-circuiting version of `Zip`. Se...
<A, B> { a: A, b: B, } impl<A, B> Iterator for LongestZip<A, B> where A: Iterator, B: Iterator { type Item = (Option<A::Item>, Option<B::Item>); fn next(&mut self) -> Option<Self::Item> { let v_a = self.a.next(); let v_b = self.b.next(); if v_a.is_some() || v_b.is_some() { ...
LongestZip
identifier_name
iter.rs
// Copyright (c) 2016, ilammy // // Licensed under MIT license (see LICENSE file in the root directory). // This file may be copied, distributed, and modified only in accordance // with the terms specified by this license. //! Iterator utilities. use std::iter::Iterator; /// Non-short-circuiting version of `Zip`. Se...
{ LongestZip { a: iter1.into_iter(), b: iter2.into_iter() } }
identifier_body
iter.rs
// Copyright (c) 2016, ilammy //
//! Iterator utilities. use std::iter::Iterator; /// Non-short-circuiting version of `Zip`. See `longest_zip()` for details. pub struct LongestZip<A, B> { a: A, b: B, } impl<A, B> Iterator for LongestZip<A, B> where A: Iterator, B: Iterator { type Item = (Option<A::Item>, Option<B::Item>); fn next(...
// Licensed under MIT license (see LICENSE file in the root directory). // This file may be copied, distributed, and modified only in accordance // with the terms specified by this license.
random_line_split
no_0216_combination_sum_iii.rs
struct Solution; impl Solution { pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> { let mut ans = Vec::new(); Self::helper(k, n, 1, &mut vec![], &mut ans); ans } fn helper(k: i32, n: i32, start: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>)
use super::*; #[test] fn test_combination_sum3() { assert_eq!(Solution::combination_sum3(3, 7), vec![vec![1, 2, 4]]); assert_eq!( Solution::combination_sum3(3, 9), vec![vec![1, 2, 6], vec![1, 3, 5], vec![2, 3, 4]] ); } }
{ if k == 0 && n == 0 && tmp.len() > 0 { ans.push(tmp.clone()); return; } for i in start..=9 { // 后面的都比 n 大了,不用再计算了。 if i > n { break; } tmp.push(i); Self::helper(k - 1, n - i, i + 1, tmp, ans); ...
identifier_body
no_0216_combination_sum_iii.rs
struct Solution; impl Solution { pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> { let mut ans = Vec::new(); Self::helper(k, n, 1, &mut vec![], &mut ans); ans } fn helper(k: i32, n: i32, start: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) { if k == 0 && n == 0 ...
for i in start..=9 { // 后面的都比 n 大了,不用再计算了。 if i > n { break; } tmp.push(i); Self::helper(k - 1, n - i, i + 1, tmp, ans); tmp.pop(); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_comb...
{ ans.push(tmp.clone()); return; }
conditional_block
no_0216_combination_sum_iii.rs
struct
; impl Solution { pub fn combination_sum3(k: i32, n: i32) -> Vec<Vec<i32>> { let mut ans = Vec::new(); Self::helper(k, n, 1, &mut vec![], &mut ans); ans } fn helper(k: i32, n: i32, start: i32, tmp: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) { if k == 0 && n == 0 && tmp.len() > ...
Solution
identifier_name