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
scorer_regression.rs
#[cfg(test)] mod scorer_regression_test { use zip::read::ZipArchive; use std::fs::File; use std::io::Read; use base::gametree::*; use base::game::*; use base::*; //#[test] fn
() { let mut total = 0; let mut total_conservative_range : usize = 0; let mut conservative_ok = 0; let mut total_optimistic_range : usize = 0; let mut optimistic_ok = 0; let mut zipf = File::open("sgfs-db/kgs-newest/dl.u-go.net/gamerecords/KGS-2015_01-19-1212-.zip").un...
it_scores_all_games_in_regression_tests
identifier_name
scorer_regression.rs
#[cfg(test)] mod scorer_regression_test { use zip::read::ZipArchive; use std::fs::File; use std::io::Read; use base::gametree::*; use base::game::*; use base::*; //#[test] fn it_scores_all_games_in_regression_tests()
if!gt.result().is_resign() &&!gt.result().is_time() { println!("Filename: {}", file.name()); let mut ok = true; let mut game = game::Game::new_for_gametree(&gt); for m in gt.moves() { ...
{ let mut total = 0; let mut total_conservative_range : usize = 0; let mut conservative_ok = 0; let mut total_optimistic_range : usize = 0; let mut optimistic_ok = 0; let mut zipf = File::open("sgfs-db/kgs-newest/dl.u-go.net/gamerecords/KGS-2015_01-19-1212-.zip").unwra...
identifier_body
scorer_regression.rs
#[cfg(test)] mod scorer_regression_test { use zip::read::ZipArchive; use std::fs::File; use std::io::Read; use base::gametree::*; use base::game::*; use base::*; //#[test] fn it_scores_all_games_in_regression_tests() { let mut total = 0; let mut total_conservative_ran...
} if ok { let cons_r = scorer::conservative_floodfill_scorer(&game); println!("Conservative est: {} real:{} is good estimation? {}", cons_r, gt.result(), cons_r.includes(gt.result())); le...
if !game.play(m.themove()) { println!("move failed: {:?}", m.themove()); ok = false; }
random_line_split
comm.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 ...
{ error!("sending"); c.send(10); error!("value sent"); }
identifier_body
comm.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 ...
(c: &Chan<int>) { error!("sending"); c.send(10); error!("value sent"); }
child
identifier_name
comm.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 _t = task::spawn(proc() child(&ch)); let y = p.recv(); error!("received"); error!("{:?}", y); assert_eq!(y, 10); } fn child(c: &Chan<int>) { error!("sending"); c.send(10); error!("value sent"); }
random_line_split
sum.rs
#![crate_name = "uu_sum"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uu...
else { println!("{} {}", sum, blocks); } } 0 }
{ println!("{} {} {}", sum, blocks, file); }
conditional_block
sum.rs
#![crate_name = "uu_sum"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uu...
pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("r", "", "use the BSD compatible algorithm (default)"); opts.optflag("s", "sysv", "use System V compatible algorithm"); opts.optflag("h", "help", "show this help message"); opts.optflag("v", "version", ...
{ match name { "-" => Ok(Box::new(stdin()) as Box<Read>), _ => { let f = try!(File::open(&Path::new(name))); Ok(Box::new(f) as Box<Read>) } } }
identifier_body
sum.rs
#![crate_name = "uu_sum"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uu...
(mut reader: Box<Read>) -> (usize, u16) { let mut buf = [0; 1024]; let mut blocks_read = 0; let mut checksum: u16 = 0; loop { match reader.read(&mut buf) { Ok(n) if n!= 0 => { blocks_read += 1; for &byte in buf[..n].iter() { checksu...
bsd_sum
identifier_name
sum.rs
#![crate_name = "uu_sum"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uu...
blocks_read += 1; for &byte in buf[..n].iter() { ret = ret.wrapping_add(byte as u32); } }, _ => break, } } ret = (ret & 0xffff) + (ret >> 16); ret = (ret & 0xffff) + (ret >> 16); (blocks_read, ret as u1...
loop { match reader.read(&mut buf) { Ok(n) if n != 0 => {
random_line_split
lib.rs
pub mod checksum; use crate::checksum::Result; use pretty_toa::ThousandsSep; use std::io::Write; use std::path::PathBuf; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; pub fn print_res(samples: &[i64; 32]) { let mut stdout = StandardStream::stdout(ColorChoice::Always); let min = ...
writeln!(&mut stdout, "Std. Deviation: {} ", stddev.thousands_sep()).unwrap(); } pub fn bench_checksum(msg: String, songs: &Vec<PathBuf>, f: &dyn Fn(&PathBuf) -> Result) { let mut stdout = StandardStream::stdout(ColorChoice::Always); stdout .set_color(ColorSpec::new().set_fg(Some(Color::White))) ...
write!(&mut stdout, "---- ").unwrap(); stdout .set_color(ColorSpec::new().set_fg(Some(Color::Magenta))) .unwrap();
random_line_split
lib.rs
pub mod checksum; use crate::checksum::Result; use pretty_toa::ThousandsSep; use std::io::Write; use std::path::PathBuf; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; pub fn print_res(samples: &[i64; 32])
write!(&mut stdout, "Min: {}", min.thousands_sep()).unwrap(); stdout .set_color(ColorSpec::new().set_fg(Some(Color::White))) .unwrap(); write!(&mut stdout, " | ").unwrap(); stdout .set_color(ColorSpec::new().set_fg(Some(Color::Red))) .unwrap(); write!(&mut stdout, "Max: {...
{ let mut stdout = StandardStream::stdout(ColorChoice::Always); let min = samples.iter().min().unwrap(); let max = samples.iter().max().unwrap(); let avg: i64 = samples.iter().sum::<i64>() / samples.len() as i64; let stddev = (samples .iter() .map(|v| (v - avg) as f64) .map(...
identifier_body
lib.rs
pub mod checksum; use crate::checksum::Result; use pretty_toa::ThousandsSep; use std::io::Write; use std::path::PathBuf; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; pub fn print_res(samples: &[i64; 32]) { let mut stdout = StandardStream::stdout(ColorChoice::Always); let min = ...
(msg: String, songs: &Vec<PathBuf>, f: &dyn Fn(&PathBuf) -> Result) { let mut stdout = StandardStream::stdout(ColorChoice::Always); stdout .set_color(ColorSpec::new().set_fg(Some(Color::White))) .unwrap(); writeln!(&mut stdout, "{}", msg).unwrap(); for song in songs { let mut samp...
bench_checksum
identifier_name
main.rs
#[macro_use] extern crate lazy_static; extern crate regex; use std::str::FromStr; use std::io::Read; #[derive(Debug)] enum IngestionState { Take, Duplicate { occ: usize, rem: usize, buf: String } } fn parse_marker(s: &str) -> (usize, usize) { let (occ, rep) = s.split_at(s.find...
(s: &str) -> IngestionState { let (len, rep) = parse_marker(s); Duplicate { rem: len, occ: rep, buf: String::new() } } } #[derive(Debug)] struct Decompressor { decompressed: String, state: IngestionState, } #[derive(Debug)] enum BlockType { W...
from_marker
identifier_name
main.rs
#[macro_use] extern crate lazy_static; extern crate regex; use std::str::FromStr; use std::io::Read; #[derive(Debug)] enum IngestionState { Take, Duplicate { occ: usize, rem: usize, buf: String } } fn parse_marker(s: &str) -> (usize, usize) { let (occ, rep) = s.split_at(s.find...
} fn split(compressed: &str) -> Vec<(BlockType, &str)> { let mut blocks = Vec::new(); lazy_static! { static ref RE: regex::Regex = regex::Regex::new("(\\w+)?(\\(\\w+\\))?").unwrap(); } for cap in RE.captures_iter(compressed) { if let Some(s) = cap.at(1) { blocks.push((BlockTy...
Marker
random_line_split
main.rs
#[macro_use] extern crate lazy_static; extern crate regex; use std::str::FromStr; use std::io::Read; #[derive(Debug)] enum IngestionState { Take, Duplicate { occ: usize, rem: usize, buf: String } } fn parse_marker(s: &str) -> (usize, usize) { let (occ, rep) = s.split_at(s.find...
*rem -= block.1.len(); } } } if switch_to_take { decomp.state = Take; } } fn decompress(s: &str) -> String { let mut decompressor = Decompressor {decompressed: String::new(), state: Take}; for b in split(s) { ingest_block(&mut decompressor, b) ...
{ let mut switch_to_take = false; match (&mut decomp.state, block.0) { (&mut Take, Word) => decomp.decompressed += block.1, (s @ &mut Take, Marker) => *s = IngestionState::from_marker(block.1), (&mut Duplicate {ref occ, ref mut rem, ref mut buf}, _) => { ...
identifier_body
protocol.rs
// Copyright 2019 Google LLC // // 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 ...
match header_name.as_ref() { "content-length:" => { size = Some(usize::from_str_radix(header_value, 10).map_err(|_e| { io::Error::new(io::ErrorKind::InvalidData, "Couldn't read size") })?); } "content-type:" => { ...
let header_name = res[0].to_lowercase(); let header_value = res[1].trim();
random_line_split
protocol.rs
// Copyright 2019 Google LLC // // 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 ...
{ std::io::stdout().write(format!("Content-Length: {}\r\n\r\n", content.len()).as_bytes())?; std::io::stdout().write(content.as_bytes())?; std::io::stdout().flush()?; Ok(()) }
identifier_body
protocol.rs
// Copyright 2019 Google LLC // // 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 ...
<R: BufRead>(input: &mut R) -> Result<String, io::Error> { // Read in the "Content-Length: xx" part. let mut size: Option<usize> = None; loop { let mut buffer = String::new(); input.read_line(&mut buffer)?; // End of input. if buffer.is_empty() { return Err(io::E...
read_message
identifier_name
crc.rs
// Pre-generated crc-8 table. // // Using the polynomial, x^8 + x^2 + x^1 + x^0 (0b1_00000111) and the // initial value of zero, each array entry is evaluated. // // Algorithm for generating this table: // // ``` // // The polynomial get shrunk down to a u8 even with it being a 9 bit // // value. // let polynomial ...
#[test] fn test_crc16() { assert_eq!(crc16(&[0x00, 0x0a]), 0x003c); assert_eq!(crc16(&[0x80, 0x05, 0x80, 0xbb]), 0x03e8); assert_eq!(crc16(&[0x00, 0x6c, 0x01, 0x92, 0x02, 0xd0]), 0x02a8); assert_eq!(crc16(&[0x00, 0xaa]), 0x03fc); assert_eq!(crc16(&[0x80, 0xb1, 0x83, 0xa9]), 0x0014); assert...
{ assert_eq!(crc8(&[0x1f]), 0x5d); assert_eq!(crc8(&[0x04, 0x01]), 0x53); assert_eq!(crc8(&[0x61, 0x62, 0x63]), 0x5f); assert_eq!(crc8(&[0x94]), 0xe5); assert_eq!(crc8(&[0x36, 0xa7]), 0xfb); assert_eq!(crc8(&[0x4f, 0x9e, 0x4b]), 0x00); }
identifier_body
crc.rs
// Pre-generated crc-8 table. // // Using the polynomial, x^8 + x^2 + x^1 + x^0 (0b1_00000111) and the // initial value of zero, each array entry is evaluated. // // Algorithm for generating this table: // // ``` // // The polynomial get shrunk down to a u8 even with it being a 9 bit // // value. // let polynomial ...
#[test] fn test_crc8() { assert_eq!(crc8(&[0x1f]), 0x5d); assert_eq!(crc8(&[0x04, 0x01]), 0x53); assert_eq!(crc8(&[0x61, 0x62, 0x63]), 0x5f); assert_eq!(crc8(&[0x94]), 0xe5); assert_eq!(crc8(&[0x36, 0xa7]), 0xfb); assert_eq!(crc8(&[0x4f, 0x9e, 0x4b]), 0x00); } #[test] fn test_crc16() ...
#[cfg(test)] mod tests { use super::*;
random_line_split
crc.rs
// Pre-generated crc-8 table. // // Using the polynomial, x^8 + x^2 + x^1 + x^0 (0b1_00000111) and the // initial value of zero, each array entry is evaluated. // // Algorithm for generating this table: // // ``` // // The polynomial get shrunk down to a u8 even with it being a 9 bit // // value. // let polynomial ...
(data: &[u8]) -> u16 { data.iter().fold(0, |crc, byte| { let index = (((crc >> 8) as u8) ^ byte) as usize; (crc << 8) ^ unsafe { *CRC_16_TABLE.get_unchecked(index) } }) } #[cfg(test)] mod tests { use super::*; #[test] fn test_crc8() { assert_eq!(crc8(&[0x1f]), 0x5d); assert_eq!(crc8(&[0x04,...
crc16
identifier_name
client_async.rs
extern crate solicit; use solicit::http::Header;
fn main() { // Connect to a server that supports HTTP/2 let connector = CleartextConnector::new("http2bin.org"); let client = Client::with_connector(connector).unwrap(); // Issue 5 requests from 5 different threads concurrently and wait for all // threads to receive their response. let threads...
use solicit::client::Client; use solicit::http::client::CleartextConnector; use std::thread; use std::str;
random_line_split
client_async.rs
extern crate solicit; use solicit::http::Header; use solicit::client::Client; use solicit::http::client::CleartextConnector; use std::thread; use std::str; fn main()
println!(" {}: {}", str::from_utf8(header.name()).unwrap(), str::from_utf8(header.value()).unwrap()); } println!("Body:"); println!("{}", str::from_utf8(&response.body).unwrap()); }) }).collect(); let _: Ve...
{ // Connect to a server that supports HTTP/2 let connector = CleartextConnector::new("http2bin.org"); let client = Client::with_connector(connector).unwrap(); // Issue 5 requests from 5 different threads concurrently and wait for all // threads to receive their response. let threads: Vec<_> = ...
identifier_body
client_async.rs
extern crate solicit; use solicit::http::Header; use solicit::client::Client; use solicit::http::client::CleartextConnector; use std::thread; use std::str; fn
() { // Connect to a server that supports HTTP/2 let connector = CleartextConnector::new("http2bin.org"); let client = Client::with_connector(connector).unwrap(); // Issue 5 requests from 5 different threads concurrently and wait for all // threads to receive their response. let threads: Vec<_>...
main
identifier_name
keypad.rs
// keypad.rs --- // // Filename: keypad.rs // Author: Jules <archjules> // Created: Wed Mar 22 17:07:36 2017 (+0100) // Last-Updated: Wed Mar 22 17:17:14 2017 (+0100) // By: Jules <archjules> // pub struct Keypad { a_button: bool, b_button: bool, select: bool, start: bool, right: bool,...
} } pub fn get_keyinput(&self) -> u16 { (self.a_button as u16) | ((self.b_button as u16) << 1) | ((self.select as u16) << 2) | ((self.start as u16) << 3) | ((self.right as u16) << 4) | ((self.left as u16) << 5) | ((self.up as u16) << 6) | ...
down: false, r_button: false, l_button: false,
random_line_split
keypad.rs
// keypad.rs --- // // Filename: keypad.rs // Author: Jules <archjules> // Created: Wed Mar 22 17:07:36 2017 (+0100) // Last-Updated: Wed Mar 22 17:17:14 2017 (+0100) // By: Jules <archjules> // pub struct Keypad { a_button: bool, b_button: bool, select: bool, start: bool, right: bool,...
pub fn get_keyinput(&self) -> u16 { (self.a_button as u16) | ((self.b_button as u16) << 1) | ((self.select as u16) << 2) | ((self.start as u16) << 3) | ((self.right as u16) << 4) | ((self.left as u16) << 5) | ((self.up as u16) << 6) | ((self.down as ...
{ Keypad { a_button: false, b_button: false, select: false, start: false, right: false, left: false, up: false, down: false, r_button: false, l_button: false, } }
identifier_body
keypad.rs
// keypad.rs --- // // Filename: keypad.rs // Author: Jules <archjules> // Created: Wed Mar 22 17:07:36 2017 (+0100) // Last-Updated: Wed Mar 22 17:17:14 2017 (+0100) // By: Jules <archjules> // pub struct Keypad { a_button: bool, b_button: bool, select: bool, start: bool, right: bool,...
() -> Keypad { Keypad { a_button: false, b_button: false, select: false, start: false, right: false, left: false, up: false, down: false, r_button: false, l_button: false, } } ...
new
identifier_name
drop-order.rs
// run-pass //! Test that let bindings and destructuring assignments have consistent drop orders #![feature(destructuring_assignment)] #![allow(unused_variables, unused_assignments)] use std::cell::RefCell; thread_local! { static DROP_ORDER: RefCell<Vec<usize>> = RefCell::new(Vec::new()); } struct DropRecorder...
() { let expected_drop_order = vec![1, 4, 5, 3, 2]; // Check the drop order for let bindings: { let _ = DropRecorder(1); let _val = DropRecorder(2); let (x, _) = (DropRecorder(3), DropRecorder(4)); drop(DropRecorder(5)); } DROP_ORDER.with(|d| { assert_eq!(&*d....
main
identifier_name
drop-order.rs
// run-pass //! Test that let bindings and destructuring assignments have consistent drop orders #![feature(destructuring_assignment)] #![allow(unused_variables, unused_assignments)] use std::cell::RefCell; thread_local! { static DROP_ORDER: RefCell<Vec<usize>> = RefCell::new(Vec::new()); }
} fn main() { let expected_drop_order = vec![1, 4, 5, 3, 2]; // Check the drop order for let bindings: { let _ = DropRecorder(1); let _val = DropRecorder(2); let (x, _) = (DropRecorder(3), DropRecorder(4)); drop(DropRecorder(5)); } DROP_ORDER.with(|d| { asser...
struct DropRecorder(usize); impl Drop for DropRecorder { fn drop(&mut self) { DROP_ORDER.with(|d| d.borrow_mut().push(self.0)); }
random_line_split
testing.rs
// The MIT License (MIT) // // Copyright (c) 2014 Jeremy Letang (letang.jeremy@gmail.com) // // 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 limitati...
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SO...
// copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
random_line_split
cndtr.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * 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 distribute...
cndtr.set_ndt(5); assert_eq!(cndtr.0, 5); } // TODO: Tests for out of range values? }
assert_eq!(cndtr.0, 65535);
random_line_split
cndtr.rs
/* * Copyright (C) 2017 AltOS-Rust Team * * 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 distribute...
(u32); impl CNDTR { /* Bits 31:16 Reserved, must be kept at reset value. * Bits 15:0 NDT[15:0]: Number of data to transfer * * Number of data to be transferred (0 up to 65535). * * This register can only be written when the channel is disabled. * Once the channel is enabled, this re...
CNDTR
identifier_name
fast_forward.rs
use std::io; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::super::{RequestType, Request}; use ::proto::{self, Deserialize, Serialize}; #[derive(Debug, Clone)] pub enum FastForward { TrackBoundary = 0, } impl Deserialize for FastForward { fn read(buf: &mut io::Cursor<Vec<u8>>) -> io::Re...
} impl Serialize for FastForwardError { fn write(&self, buf: &mut io::Cursor<Vec<u8>>) -> io::Result<()> { try!(proto::write_empty_struct(buf)); Ok(()) } }
{ try!(proto::read_empty_struct(buf)); Ok(FastForwardError) }
identifier_body
fast_forward.rs
use std::io; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::super::{RequestType, Request}; use ::proto::{self, Deserialize, Serialize}; #[derive(Debug, Clone)] pub enum FastForward { TrackBoundary = 0, } impl Deserialize for FastForward { fn read(buf: &mut io::Cursor<Vec<u8>>) -> io::Re...
(&self, buf: &mut io::Cursor<Vec<u8>>) -> io::Result<()> { try!(proto::write_empty_struct(buf)); Ok(()) } }
write
identifier_name
fast_forward.rs
use std::io; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::super::{RequestType, Request}; use ::proto::{self, Deserialize, Serialize}; #[derive(Debug, Clone)] pub enum FastForward { TrackBoundary = 0, } impl Deserialize for FastForward { fn read(buf: &mut io::Cursor<Vec<u8>>) -> io::Re...
let kind = match kind { Some(kind) => kind, None => return Err(io::Error::new(io::ErrorKind::Other, "missing field: kind")), }; Ok(FastForwardRequest { kind: kind, }) } } impl Serialize for FastForwardRequest { fn write(&self, buf: &mut io::...
random_line_split
generate_lockfile.rs
use std::os; use cargo::ops; use cargo::core::MultiShell; use cargo::util::{CliResult, CliError}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct
{ flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for ...
Options
identifier_name
generate_lockfile.rs
use std::os; use cargo::ops; use cargo::core::MultiShell; use cargo::util::{CliResult, CliError}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, } pub const USAGE: &'static str = " Generate the l...
{ debug!("executing; cmd=cargo-generate-lockfile; args={:?}", os::args()); shell.set_verbose(options.flag_verbose); let root = try!(find_root_manifest_for_cwd(options.flag_manifest_path)); ops::generate_lockfile(&root, shell) .map(|_| None).map_err(|err| CliError::from_boxed(err, 101)) }
identifier_body
generate_lockfile.rs
use std::os; use cargo::ops; use cargo::core::MultiShell; use cargo::util::{CliResult, CliError}; use cargo::util::important_paths::find_root_manifest_for_cwd; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_verbose: bool, }
pub const USAGE: &'static str = " Generate the lockfile for a project Usage: cargo generate-lockfile [options] Options: -h, --help Print this message --manifest-path PATH Path to the manifest to generate a lockfile for -v, --verbose Use verbose output "; pub fn execute(optio...
random_line_split
lib.rs
/*! A Rust syntax extension for applying the `pub` visibility modifer to many items at once Right now the attribute applies to every possible child AST element that could have public visibility, including: - `use` - `static` - `fn`, both standalone and methods/associated ones - `mod` - `type`, `struct` and `enum` - `...
(self) -> bool { match self { IsFn => true, _ => false } } fn is_trait_impl(self) -> bool { match self { IsTraitImpl => true, _ => false } } fn is_type_impl(self) -> bool { match self { IsTypeImpl => true, _ => false } } fn is_extern_block(self) -> bool { match self { IsExternBlock => true, _ => false } } ...
is_fn
identifier_name
lib.rs
/*! A Rust syntax extension for applying the `pub` visibility modifer to many items at once Right now the attribute applies to every possible child AST element that could have public visibility, including: - `use` - `static` - `fn`, both standalone and methods/associated ones - `mod` - `type`, `struct` and `enum` - `...
#[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_syntax_extension(token::intern(NAME), SyntaxExtension::Modifier(box Expand)); } struct ApplyPubFolder { parent_item_variant: ItemVariant } struct Expand; impl ItemModifier for Expand { fn expand(&self, ecx: &mut ...
random_line_split
service.rs
extern crate proc_macro; use std::convert::From; use syn; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{quote,ToTokens}; use super::utils::*; struct Service<'a> { ast: &'a syn::ItemImpl, idents: Vec<syn::Ident>, idents_cap: Vec<syn::Ident>, args: Vec<Vec<syn:...
#(fn #idents(&mut self, #(#args: #args_ty),*) -> Box<Future<Output=Result<#outputs,()>>> { Box::new(self.send_request(Request::#idents_cap(#(#args),*)) .then(|response| match response { #variants, _ => err...
random_line_split
service.rs
extern crate proc_macro; use std::convert::From; use syn; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{quote,ToTokens}; use super::utils::*; struct Service<'a> { ast: &'a syn::ItemImpl, idents: Vec<syn::Ident>, idents_cap: Vec<syn::Ident>, args: Vec<Vec<syn:...
fn types(&self) -> TokenStream2 { let Self { idents_cap, args_ty, outputs,.. } = self; let (_impl_generics, ty_generics, where_clause) = self.ast.generics.split_for_impl(); // we need phantom variant for handling generics cases: R, R<A>, R<A,B>. let phantom = quote! { _Phantom(Pha...
{ let ast = &self.ast; let (types, server, client) = (self.types(), self.server(), self.client()); (quote!{ #ast pub mod service { use super::*; use libfoxlive::rpc::Service; use std::marker::PhantomData; u...
identifier_body
service.rs
extern crate proc_macro; use std::convert::From; use syn; use proc_macro::TokenStream; use proc_macro2::TokenStream as TokenStream2; use quote::{quote,ToTokens}; use super::utils::*; struct Service<'a> { ast: &'a syn::ItemImpl, idents: Vec<syn::Ident>, idents_cap: Vec<syn::Ident>, args: Vec<Vec<syn:...
(ast: &'a syn::ItemImpl) -> Self { let signatures = ast.items.iter().filter_map(|item| match item { syn::ImplItem::Method(item) => Some(&item.sig), _ => None, }); let (mut idents, mut idents_cap, mut args, mut args_ty, mut outputs) = (Vec::new(), Vec::new(), ...
new
identifier_name
nproc.rs
#![crate_name = "uu_nproc"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate num_cpus; #[cfg(unix)] ...
(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag( "", "all", "print the number of cores available to the system", ); opts.optopt("", "ignore", "ignore up to N cores", "N"); opts.optflag("h", "help", "display this help and exit"); opts.opt...
uumain
identifier_name
nproc.rs
#![crate_name = "uu_nproc"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate num_cpus; #[cfg(unix)] ...
{ num_cpus::get() }
identifier_body
nproc.rs
#![crate_name = "uu_nproc"] /* * This file is part of the uutils coreutils package. * * (c) Michael Gehring <mg@ebfe.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate num_cpus; #[cfg(unix)] ...
"", "all", "print the number of cores available to the system", ); opts.optopt("", "ignore", "ignore up to N cores", "N"); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.p...
random_line_split
namespace.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/. */ #[deriving(Eq, Clone)] pub enum Namespace { Null, HTML, XML, XMLNS, XLink, SVG, MathML...
match url { "http://www.w3.org/1999/xhtml" => HTML, "http://www.w3.org/XML/1998/namespace" => XML, "http://www.w3.org/2000/xmlns/" => XMLNS, "http://www.w3.org/1999/xlink" => XLink, "http://www.w3.org/2000/svg" => SVG, "http://www.w3.org/19...
pub fn from_str(url: &str) -> Namespace {
random_line_split
namespace.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/. */ #[deriving(Eq, Clone)] pub enum Namespace { Null, HTML, XML, XMLNS, XLink, SVG, MathML...
(url: &str) -> Namespace { match url { "http://www.w3.org/1999/xhtml" => HTML, "http://www.w3.org/XML/1998/namespace" => XML, "http://www.w3.org/2000/xmlns/" => XMLNS, "http://www.w3.org/1999/xlink" => XLink, "http://www.w3.org/2000/svg" => SVG, ...
from_str
identifier_name
namespace.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/. */ #[deriving(Eq, Clone)] pub enum Namespace { Null, HTML, XML, XMLNS, XLink, SVG, MathML...
}
{ match *self { Null => "", HTML => "http://www.w3.org/1999/xhtml", XML => "http://www.w3.org/XML/1998/namespace", XMLNS => "http://www.w3.org/2000/xmlns/", XLink => "http://www.w3.org/1999/xlink", SVG => "http://www.w3.org/2000/svg", ...
identifier_body
cargo_rerast_tests.rs
use assert_cmd::prelude::*; use predicates::prelude::*; use std::process::Command; fn cargo_rerast(crate_root: &str) -> Command { // We can't use Assert.current_dir, because then Assert::cargo_binary doesn't work, instead we // pass the crate root as an argument and get our binary to change directories once it...
@@ -8,7 +8,7 @@ mod tests2 { #[test] fn x() { - if 1 > 42 { + if 42 < 1 { assert!(false); } } @@ -16,7 +16,7 @@ /// A well documented function. pub fn foo(a: i32, b: i32) -> i32 { - if a > b { + if b < a { 42 } else { b @@ -26,7 +26,...
.assert() .stdout(predicate::eq( r#"--- src/lib.rs +++ src/lib.rs
random_line_split
cargo_rerast_tests.rs
use assert_cmd::prelude::*; use predicates::prelude::*; use std::process::Command; fn cargo_rerast(crate_root: &str) -> Command { // We can't use Assert.current_dir, because then Assert::cargo_binary doesn't work, instead we // pass the crate root as an argument and get our binary to change directories once it...
() { cargo_rerast("tests/crates/invalid_cargo_toml") .args(&["-s", "file!()", "-r", "\"foo\""]) .args(&["--diff", "--color=never"]) .assert() .failure() .stderr( predicate::str::contains("cargo metadata failed") .and(predicate::str::contains("could not p...
test_invalid_cargo_toml
identifier_name
cargo_rerast_tests.rs
use assert_cmd::prelude::*; use predicates::prelude::*; use std::process::Command; fn cargo_rerast(crate_root: &str) -> Command { // We can't use Assert.current_dir, because then Assert::cargo_binary doesn't work, instead we // pass the crate root as an argument and get our binary to change directories once it...
- if 1 > 42 { + if 42 < 1 { assert!(false); } } @@ -16,7 +16,7 @@ /// A well documented function. pub fn foo(a: i32, b: i32) -> i32 { - if a > b { + if b < a { 42 } else { b @@ -26,7 +26,7 @@ #[cfg(test)] mod tests { fn bar(a: i32, b: i3...
{ cargo_rerast("tests/crates/simple") // TODO: Remove once #10 is fixed. .env("RERAST_FULL_CARGO_CLEAN", "1") .arg("-p") .arg("p0: i32, p1: i32") .arg("-s") .arg("p0 > p1") .arg("-r") .arg("p1 < p0") .arg("--diff") .arg("--color=never")...
identifier_body
main.rs
#[macro_use] extern crate clap; extern crate log; #[cfg(unix)] extern crate psutil; extern crate strsim; extern crate libc; extern crate term; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate kernel32; use clap::{Arg, App}; #[cfg(unix)] use psutil::process::Process; use strsim::damerau_levens...
terminal.fg(term::color::RED).unwrap(); println!("Suspicious: {} <-> {} : distance {}", sys_proc.name, crit_proc.name, threshold); terminal.reset().unwrap(); susp_procs += 1; } } } susp_procs } #[cfg(unix)] f...
{ let mut susp_procs: u32 = 0; for sys_proc in sys_procs_vec.iter() { if *verb_mode { terminal.fg(term::color::BRIGHT_GREEN).unwrap(); println!("> Checking system process: {}", sys_proc.name); println!("> system process executable absolute path: {}", sys_proc.exe_pat...
identifier_body
main.rs
#[macro_use] extern crate clap; extern crate log; #[cfg(unix)] extern crate psutil; extern crate strsim; extern crate libc; extern crate term; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate kernel32; use clap::{Arg, App}; #[cfg(unix)] use psutil::process::Process; use strsim::damerau_levens...
// Read whole file line by line, and unwrap each line let reader = BufReader::new(file); let lines = reader.lines().map(|l| l.unwrap()); for line in lines { // Split each line into a vector let v: Vec<_> = line.split(';').map(|s| s.to_string()).collect(); assert!(v.len() >= 3,...
Ok(file) => file, }; let mut procs = Vec::new();
random_line_split
main.rs
#[macro_use] extern crate clap; extern crate log; #[cfg(unix)] extern crate psutil; extern crate strsim; extern crate libc; extern crate term; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate kernel32; use clap::{Arg, App}; #[cfg(unix)] use psutil::process::Process; use strsim::damerau_levens...
(crit_procs_vec: &Vec<types::ProcProps>, sys_procs_vec : &Vec<Process>, verb_mode : &bool, terminal : &mut Box<term::StdoutTerminal>) -> u32 { // Number of suspicious processes let mut susp_procs: u32 = 0; for sys_pro...
unix_check_procs_impers
identifier_name
main.rs
#[macro_use] extern crate clap; extern crate log; #[cfg(unix)] extern crate psutil; extern crate strsim; extern crate libc; extern crate term; #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate kernel32; use clap::{Arg, App}; #[cfg(unix)] use psutil::process::Process; use strsim::damerau_levens...
for crit_proc in crit_procs_vec.iter() { let threshold = damerau_levenshtein(&sys_proc.comm, &crit_proc.name); if *verb_mode { terminal.fg(term::color::CYAN).unwrap(); println!( "\tagainst critical process: {}, distance: {}", crit_proc.name, threshold); ...
{ terminal.fg(term::color::BRIGHT_GREEN).unwrap(); println!("> Checking system process: {}", sys_proc.comm); println!("> system process executable absolute path: {}", exe_path.to_str().unwrap()); }
conditional_block
server.rs
use std::{ iter::FromIterator, net::TcpListener, process, sync::mpsc, thread, time::Duration }; use std::convert::Infallible; use std::net::{IpAddr, SocketAddr}; use futures::channel::oneshot::channel; use hyper::server::Server; use hyper::service::make_service_fn; use log::*; use maplit::*; use serde_json...
<'a>() -> WebmachineResource<'a> { WebmachineResource { allowed_methods: vec!["POST"], forbidden: callback(&|context, _| { let options = SERVER_OPTIONS.lock().unwrap(); !context.request.has_header_value(&"Authorization".to_owned(), &format!("Bearer {}", options.borrow().server_key)) }), pro...
shutdown_resource
identifier_name
server.rs
use std::{ iter::FromIterator, net::TcpListener, process, sync::mpsc, thread, time::Duration }; use std::convert::Infallible; use std::net::{IpAddr, SocketAddr}; use futures::channel::oneshot::channel; use hyper::server::Server; use hyper::service::make_service_fn; use log::*; use maplit::*; use serde_json...
Err(err) => Err(err) } }), ..WebmachineResource::default() } } fn mock_server_resource<'a>() -> WebmachineResource<'a> { WebmachineResource { allowed_methods: vec!["OPTIONS", "GET", "HEAD", "POST", "DELETE"], resource_exists: callback(&|context, _| { debug!("mock_server_resource...
{ // Need to work out how to do this as the webmachine has to have a static lifetime // shutdown.send(()).unwrap_or_default(); thread::spawn(move || { info!("Scheduling master server to shutdown in {}ms", period); thread::sleep(Duration::from_millis(period)); ...
conditional_block
server.rs
use std::{ iter::FromIterator, net::TcpListener, process, sync::mpsc, thread, time::Duration }; use std::convert::Infallible; use std::net::{IpAddr, SocketAddr}; use futures::channel::oneshot::channel; use hyper::server::Server; use hyper::service::make_service_fn; use log::*; use maplit::*; use serde_json...
} } } }, Err(_) => Err(422) } } fn shutdown_resource<'a>() -> WebmachineResource<'a> { WebmachineResource { allowed_methods: vec!["POST"], forbidden: callback(&|context, _| { let options = SERVER_OPTIONS.lock().unwrap(); !context.request.has_header_value(&"Author...
{ let id = context.metadata.get("id").cloned().unwrap_or_default(); match verify::validate_id(&id, &SERVER_MANAGER) { Ok(ms) => { let mut map = btreemap!{ "mockServer" => ms.to_json() }; let mismatches = ms.mismatches(); if !mismatches.is_empty() { map.insert("mismatches", json!( ...
identifier_body
server.rs
use std::{ iter::FromIterator, net::TcpListener, process, sync::mpsc, thread, time::Duration }; use std::convert::Infallible; use std::net::{IpAddr, SocketAddr}; use futures::channel::oneshot::channel; use hyper::server::Server; use hyper::service::make_service_fn; use log::*; use maplit::*; use serde_json...
Ok(res) => { debug!("Result of thread: {:?}", res); let ctx = rx2.recv().unwrap(); context.response = ctx.response; res }, Err(err) => { error!("Failed to spawn new thread to start new mock server - {:?}", err); ...
match thread::spawn(start_fn).join() {
random_line_split
array.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
{ pub device_type: usize, pub device_id: usize, } impl<'a> From<&'a TVMContext> for DLContext { fn from(ctx: &'a TVMContext) -> Self { Self { device_type: ctx.device_type as u32, device_id: ctx.device_id as i32, } } } impl Default for TVMContext { fn defaul...
TVMContext
identifier_name
array.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
let typ = TypeId::of::<T>(); (typ == TypeId::of::<i32>() && self.code == 0 && self.bits == 32) || (typ == TypeId::of::<i64>() && self.code == 0 && self.bits == 64) || (typ == TypeId::of::<u32>() && self.code == 1 && self.bits == 32) || (typ == TypeId::of::<u64>() && ...
{ return false; }
conditional_block
array.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
} impl From<DLDataType> for DataType { fn from(dtype: DLDataType) -> Self { Self { code: dtype.code as usize, bits: dtype.bits as usize, lanes: dtype.lanes as usize, } } } #[derive(Debug, Clone, Copy, PartialEq)] pub struct TVMContext { pub device_type: ...
bits: dtype.bits as u8, lanes: dtype.lanes as u16, } }
random_line_split
array.rs
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
pub fn code(&self) -> usize { self.code } pub fn bits(&self) -> usize { self.bits } pub fn lanes(&self) -> usize { self.lanes } } impl<'a> From<&'a DataType> for DLDataType { fn from(dtype: &'a DataType) -> Self { Self { code: dtype.code as u8...
{ if self.lanes != 1 { return false; } let typ = TypeId::of::<T>(); (typ == TypeId::of::<i32>() && self.code == 0 && self.bits == 32) || (typ == TypeId::of::<i64>() && self.code == 0 && self.bits == 64) || (typ == TypeId::of::<u32>() && self.code == 1 ...
identifier_body
unit_properties.rs
#[derive(Debug, Clone, PartialEq)] pub struct UnitProperties { pub name: String, pub hero: bool, pub wizard: bool, pub points_per_model: f32, pub max_unit_size: i32, pub base_move_in: i32, pub flying: bool, pub save_standard: Option<i32>, pub save_mortal: Option<i32>, pub bravery...
impl UnitProperties { pub fn new( name: String, hero: bool, wizard: bool, points_per_model: f32, max_unit_size: i32, base_move_in: i32, flying: bool, save_standard: Option<i32>, save_mortal: Option<i32>, bravery: i32, ) -> Self { ...
random_line_split
unit_properties.rs
#[derive(Debug, Clone, PartialEq)] pub struct UnitProperties { pub name: String, pub hero: bool, pub wizard: bool, pub points_per_model: f32, pub max_unit_size: i32, pub base_move_in: i32, pub flying: bool, pub save_standard: Option<i32>, pub save_mortal: Option<i32>, pub bravery...
( name: String, hero: bool, wizard: bool, points_per_model: f32, max_unit_size: i32, base_move_in: i32, flying: bool, save_standard: Option<i32>, save_mortal: Option<i32>, bravery: i32, ) -> Self { UnitProperties { n...
new
identifier_name
unit_properties.rs
#[derive(Debug, Clone, PartialEq)] pub struct UnitProperties { pub name: String, pub hero: bool, pub wizard: bool, pub points_per_model: f32, pub max_unit_size: i32, pub base_move_in: i32, pub flying: bool, pub save_standard: Option<i32>, pub save_mortal: Option<i32>, pub bravery...
}
{ UnitProperties { name: name, hero: hero, wizard: wizard, points_per_model: points_per_model, max_unit_size: max_unit_size, base_move_in: base_move_in, flying: flying, save_standard: save_standard, save_...
identifier_body
blocks.rs
use ansi_term::Style; use crate::fs::fields as f; use crate::output::cell::TextCell; impl f::Blocks { pub fn render<C: Colours>(&self, colours: &C) -> TextCell { match self { Self::Some(blk) => TextCell::paint(colours.block_count(), blk.to_string()), Self::None => TextCell:...
}
{ let blox = f::Blocks::Some(3005); let expected = TextCell::paint_str(Red.blink(), "3005"); assert_eq!(expected, blox.render(&TestColours).into()); }
identifier_body
blocks.rs
use ansi_term::Style; use crate::fs::fields as f; use crate::output::cell::TextCell; impl f::Blocks { pub fn render<C: Colours>(&self, colours: &C) -> TextCell { match self { Self::Some(blk) => TextCell::paint(colours.block_count(), blk.to_string()), Self::None => TextCell:...
(&self) -> Style { Green.italic() } } #[test] fn blocklessness() { let blox = f::Blocks::None; let expected = TextCell::blank(Green.italic()); assert_eq!(expected, blox.render(&TestColours).into()); } #[test] fn blockfulity() { let blox = f::Blocks::Some(30...
no_blocks
identifier_name
blocks.rs
use ansi_term::Style; use crate::fs::fields as f; use crate::output::cell::TextCell; impl f::Blocks { pub fn render<C: Colours>(&self, colours: &C) -> TextCell { match self { Self::Some(blk) => TextCell::paint(colours.block_count(), blk.to_string()), Self::None => TextCell:...
#[test] fn blockfulity() { let blox = f::Blocks::Some(3005); let expected = TextCell::paint_str(Red.blink(), "3005"); assert_eq!(expected, blox.render(&TestColours).into()); } }
}
random_line_split
game.rs
use time; use std::rand; use std::rand::Rng; use std::mem; use cgmath::point::{Point2}; use cgmath::vector::{Vec2}; use cgmath::aabb::{Aabb2}; use color::rgb::consts::*; use calx::app::App; use calx::app; use calx::renderer::Renderer; use calx::renderer; use calx::rectutil::RectUtil; use area::{Location, Area, uphil...
() -> Game { let mut ret = Game { area: ~Area::new(area::Rock), pos: Location(Point2::new(0i8, 0i8)), seen: ~Fov::new(), remembered: ~Fov::new(), mobs: ~[], player_dijkstra: None, rng: rand::rng(), stop: true, ...
new
identifier_name
game.rs
use time; use std::rand; use std::rand::Rng; use std::mem; use cgmath::point::{Point2}; use cgmath::vector::{Vec2}; use cgmath::aabb::{Aabb2}; use color::rgb::consts::*; use calx::app::App; use calx::app; use calx::renderer::Renderer; use calx::renderer; use calx::rectutil::RectUtil; use area::{Location, Area, uphil...
} } false } pub fn mob_idx_at<'a>(&'a self, loc: Location) -> Option<uint> { for (i, mob) in self.mobs.iter().enumerate() { if mob.loc == loc && mob.is_alive() { return Some(i); } } None } pub fn drawable_mob_a...
return true;
random_line_split
game.rs
use time; use std::rand; use std::rand::Rng; use std::mem; use cgmath::point::{Point2}; use cgmath::vector::{Vec2}; use cgmath::aabb::{Aabb2}; use color::rgb::consts::*; use calx::app::App; use calx::app; use calx::renderer::Renderer; use calx::renderer; use calx::rectutil::RectUtil; use area::{Location, Area, uphil...
} }
{ self.next_level(); }
conditional_block
game.rs
use time; use std::rand; use std::rand::Rng; use std::mem; use cgmath::point::{Point2}; use cgmath::vector::{Vec2}; use cgmath::aabb::{Aabb2}; use color::rgb::consts::*; use calx::app::App; use calx::app; use calx::renderer::Renderer; use calx::renderer; use calx::rectutil::RectUtil; use area::{Location, Area, uphil...
pub fn win_game(&mut self) { self.update(); self.mobs[self.player_idx()].hits = -666; self.mobs[self.player_idx()].anim_state = mob::Invisible; } pub fn smart_move(&mut self, dirs: &[Vec2<int>]) -> bool { let player_idx = self.player_idx(); for d in dirs.iter() { ...
{ let player_idx = self.player_idx(); if self.mobs[player_idx].ammo < 6 { self.msg("reload"); self.mobs[player_idx].ammo += 1; } self.update(); }
identifier_body
mod.rs
//! A bounded SPSC channel. use arc::{Arc, ArcTrait}; use select::{Selectable, _Selectable}; use {Error, Sendable}; mod imp; #[cfg(test)] mod test; #[cfg(test)] mod bench; /// Creates a new bounded SPSC channel. /// /// ### Panic /// /// Panics if `next_power_of_two(cap) * sizeof(T) >= isize::MAX`. pub fn
<'a, T: Sendable+'a>(cap: usize) -> (Producer<'a, T>, Consumer<'a, T>) { let packet = Arc::new(imp::Packet::new(cap)); packet.set_id(packet.unique_id()); (Producer { data: packet.clone() }, Consumer { data: packet }) } /// The producing half of a bounded SPSC channel. pub struct Producer<'a, T: Sendable+'a...
new
identifier_name
mod.rs
//! A bounded SPSC channel. use arc::{Arc, ArcTrait}; use select::{Selectable, _Selectable}; use {Error, Sendable}; mod imp; #[cfg(test)] mod test; #[cfg(test)] mod bench; /// Creates a new bounded SPSC channel. /// /// ### Panic /// /// Panics if `next_power_of_two(cap) * sizeof(T) >= isize::MAX`. pub fn new<'a, T:...
data: Arc<imp::Packet<'a, T>>, } impl<'a, T: Sendable+'a> Consumer<'a, T> { /// Receives a message over this channel. Blocks until a message is available. /// /// ### Errors /// /// - `Disconnected` - No message is available and the sender has disconnected. pub fn recv_sync(&self) -> Result...
unsafe impl<'a, T: Sendable+'a> Send for Producer<'a, T> { } /// The consuming half of a bounded SPSC channel. pub struct Consumer<'a, T: Sendable+'a> {
random_line_split
mod.rs
//! A bounded SPSC channel. use arc::{Arc, ArcTrait}; use select::{Selectable, _Selectable}; use {Error, Sendable}; mod imp; #[cfg(test)] mod test; #[cfg(test)] mod bench; /// Creates a new bounded SPSC channel. /// /// ### Panic /// /// Panics if `next_power_of_two(cap) * sizeof(T) >= isize::MAX`. pub fn new<'a, T:...
/// The producing half of a bounded SPSC channel. pub struct Producer<'a, T: Sendable+'a> { data: Arc<imp::Packet<'a, T>>, } impl<'a, T: Sendable+'a> Producer<'a, T> { /// Sends a message over the channel. Blocks if the buffer is full. /// /// ### Errors /// /// - `Disconnected` - The receive...
{ let packet = Arc::new(imp::Packet::new(cap)); packet.set_id(packet.unique_id()); (Producer { data: packet.clone() }, Consumer { data: packet }) }
identifier_body
mod.rs
/*! **The Conrod Guide** ## Table of Contents 1. [**What is Conrod?**][1] - [A Brief Summary][1.1] - [Screenshots and Videos][1.2] - [Feature Overview][1.3] - [Available Widgets][1.4] - [Primitive Widgets][1.4.1] - [Common Use Widgets][1.4.2] - [Immediate Mode][1.5] - [Wha...
- Making a `Button` widget 6. **Custom Graphics and Window Backends** - Demonstration of Backend Implementation (using glium and glutin) 7. **Internals** - The `Ui`'s Widget `Graph` - `Ui::set_widgets` - How does it work? 8. **FAQ** [1]: ./chapter_1/index.html [1.1]: ./chapter_1/index.html#a...
random_line_split
tokenizer.rs
use std::collections::HashSet; #[derive(PartialEq)] enum CharTypes { IsNumeric, IsAlphabetic, IsSpace, IsOther, } #[derive(Debug, PartialEq, Clone)] pub enum TokenType { IsVariable, IsNumeric, IsFunction, IsOperation, } #[derive(Debug, Clone)] pub struct Token { pub param: String,...
} // add last token to stack if last_type!= CharTypes::IsSpace { let tmp = strcpy(buffer, last_pos, curr_pos); let token_type = identify(tmp); stack.push(Token::new(tmp, token_type)); } stack }
last_pos = curr_pos; last_type = curr_type; } curr_pos += 1;
random_line_split
tokenizer.rs
use std::collections::HashSet; #[derive(PartialEq)] enum CharTypes { IsNumeric, IsAlphabetic, IsSpace, IsOther, } #[derive(Debug, PartialEq, Clone)] pub enum TokenType { IsVariable, IsNumeric, IsFunction, IsOperation, } #[derive(Debug, Clone)] pub struct Token { pub param: String,...
<'a>(buffer: &'a str) -> Vec<Token> { // unsafe copy function fn strcpy<'a>(buffer: &'a str, start: usize, stop: usize) -> &'a str { unsafe { buffer.slice_unchecked(start, stop) } } let mut stack: Vec<Token> = Vec::new(); let mut last_pos: usize = 0; let mut curr_pos: usize = 0; let ...
tokenize
identifier_name
tokenizer.rs
use std::collections::HashSet; #[derive(PartialEq)] enum CharTypes { IsNumeric, IsAlphabetic, IsSpace, IsOther, } #[derive(Debug, PartialEq, Clone)] pub enum TokenType { IsVariable, IsNumeric, IsFunction, IsOperation, } #[derive(Debug, Clone)] pub struct Token { pub param: String,...
} trait SpecTypes { fn get_type(&self) -> CharTypes; } impl SpecTypes for char { // get character type fn get_type(&self) -> CharTypes { if self.is_numeric() || *self == '.' { CharTypes::IsNumeric } else if self.is_alphabetic() { CharTypes::IsAlphabetic } e...
{ Token { param: buffer.into(), id: id, } }
identifier_body
tokenizer.rs
use std::collections::HashSet; #[derive(PartialEq)] enum CharTypes { IsNumeric, IsAlphabetic, IsSpace, IsOther, } #[derive(Debug, PartialEq, Clone)] pub enum TokenType { IsVariable, IsNumeric, IsFunction, IsOperation, } #[derive(Debug, Clone)] pub struct Token { pub param: String,...
} } fn identify(item: &str) -> TokenType { // available functions let funcs: HashSet<&'static str> = seq!["exit", "print", "read", "stack"]; // get first character from string let chr = item.chars().nth(0).unwrap(); // check character type if chr.is_numeric() { TokenType::IsNumeric...
{ CharTypes::IsOther }
conditional_block
modifiers.rs
/// Modifiers which can be injected by the application logic to change the state use ::api; use ::api::optional::Optional; /// `StatusModifier`s are used to modify the status pub trait StatusModifier: Send + Sync { /// Called after all registered sensors are read fn modify(&self, status: &mut api::Status); } ...
status.state.message = Optional::Value(format!("{} person here right now", count)); } else if count > 1 { status.state.message = Optional::Value(format!("{} people here right now", count)); } } } }
.into(); if let Some(count) = people_now_present { status.state.open = Some(count > 0); if count == 1 {
random_line_split
modifiers.rs
/// Modifiers which can be injected by the application logic to change the state use ::api; use ::api::optional::Optional; /// `StatusModifier`s are used to modify the status pub trait StatusModifier: Send + Sync { /// Called after all registered sensors are read fn modify(&self, status: &mut api::Status); } ...
} }
{ status.state.open = Some(count > 0); if count == 1 { status.state.message = Optional::Value(format!("{} person here right now", count)); } else if count > 1 { status.state.message = Optional::Value(format!("{} people here right now", count)); ...
conditional_block
modifiers.rs
/// Modifiers which can be injected by the application logic to change the state use ::api; use ::api::optional::Optional; /// `StatusModifier`s are used to modify the status pub trait StatusModifier: Send + Sync { /// Called after all registered sensors are read fn modify(&self, status: &mut api::Status); } ...
; impl StatusModifier for StateFromPeopleNowPresent { fn modify(&self, status: &mut api::Status) { // Update state depending on number of people present let people_now_present: Option<u64> = status.sensors.as_ref() .and_then(|sensors| sensors.people_now_present.as_ref()) .map(...
StateFromPeopleNowPresent
identifier_name
simd.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 ...
(i32, i32, i32, i32); extern { // _mm_sll_epi32 #[cfg(any(target_arch = "x86", target_arch = "x86-64"))] #[link_name = "llvm.x86.sse2.psll.d"] fn integer(a: i32x4, b: i32x4) -> i32x4; // vmaxq_s32 #[cfg(any(target_arch = "arm"))] #[link_name = "llvm.arm.neon.vmaxs.v4i32"] ...
i32x4
identifier_name
simd.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 ...
} #[repr(C)] #[derive(Copy)] #[simd] pub struct i32x4(i32, i32, i32, i32); extern { // _mm_sll_epi32 #[cfg(any(target_arch = "x86", target_arch = "x86-64"))] #[link_name = "llvm.x86.sse2.psll.d"] fn integer(a: i32x4, b: i32x4) -> i32x4; // vmaxq_s32 #[cfg(any(target_arch = "arm...
random_line_split
pack.rs
use std::path::Path; use unshare::{Command, Stdio}; use container::uidmap::{map_users}; use options::pack::Options; use wrapper::Wrapper; use process_util::{convert_status, set_uidmap}; use super::setup; pub fn
(wrapper: &Wrapper, cmdline: Vec<String>) -> Result<i32, String> { let options = match Options::parse(&cmdline) { Ok(x) => x, Err(code) => return Ok(code), }; try!(setup::setup_base_filesystem( wrapper.project_root, wrapper.ext_settings)); let cconfig = try!(wrapper.config.c...
pack_image_cmd
identifier_name
pack.rs
use std::path::Path; use unshare::{Command, Stdio}; use container::uidmap::{map_users}; use options::pack::Options; use wrapper::Wrapper; use process_util::{convert_status, set_uidmap}; use super::setup; pub fn pack_image_cmd(wrapper: &Wrapper, cmdline: Vec<String>) -> Result<i32, String>
false); if let Some(ref f) = options.file { cmd.arg("-f").arg(Path::new("/work").join(f)); } cmd.arg("-C").arg(&root); cmd.arg("."); info!("Running {:?}", cmd); cmd.status() .map(convert_status) .map_err(|e| format!("Command {:?} {}", cmd, e)) }
{ let options = match Options::parse(&cmdline) { Ok(x) => x, Err(code) => return Ok(code), }; try!(setup::setup_base_filesystem( wrapper.project_root, wrapper.ext_settings)); let cconfig = try!(wrapper.config.containers.get(&options.name) .ok_or(format!("Container {} not...
identifier_body
pack.rs
use std::path::Path; use unshare::{Command, Stdio}; use container::uidmap::{map_users}; use options::pack::Options; use wrapper::Wrapper; use process_util::{convert_status, set_uidmap}; use super::setup; pub fn pack_image_cmd(wrapper: &Wrapper, cmdline: Vec<String>) -> Result<i32, String> { let options = ma...
.join(container_ver).join("root"); let mut cmd = Command::new("/vagga/bin/busybox"); cmd.stdin(Stdio::null()) .arg("tar") .arg("-c"); set_uidmap(&mut cmd, &try!(map_users(wrapper.settings, &cconfig.uids, &cconfig.gids)), false); if let Some(ref f) = options.file { ...
let cconfig = try!(wrapper.config.containers.get(&options.name) .ok_or(format!("Container {} not found", options.name))); let container_ver = wrapper.root.as_ref().unwrap(); let root = Path::new("/vagga/base/.roots")
random_line_split
lib.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/. */ #![feature(alloc)] #![feature(box_syntax)] #![feature(collections)] #![feature(core)] #![feature(env)] #![feature(...
pub mod namespace; pub mod opts; pub mod persistent_list; pub mod range; pub mod resource_files; pub mod str; pub mod task; pub mod tid; pub mod time; pub mod taskpool; pub mod task_state; pub mod vec; pub mod workqueue; pub fn breakpoint() { unsafe { ::std::intrinsics::breakpoint() }; } // Workaround for lack of...
random_line_split
lib.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/. */ #![feature(alloc)] #![feature(box_syntax)] #![feature(collections)] #![feature(core)] #![feature(env)] #![feature(...
// Workaround for lack of `ptr_eq` on Arcs... #[inline] pub fn arc_ptr_eq<T:'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool { let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
{ unsafe { ::std::intrinsics::breakpoint() }; }
identifier_body
lib.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/. */ #![feature(alloc)] #![feature(box_syntax)] #![feature(collections)] #![feature(core)] #![feature(env)] #![feature(...
<T:'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool { let a: &T = &**a; let b: &T = &**b; (a as *const T) == (b as *const T) }
arc_ptr_eq
identifier_name
cs_matrix.rs
#![cfg_attr(rustfmt, rustfmt_skip)] use na::{Matrix4x5, Matrix5x4, CsMatrix}; #[test] fn
() { let m = Matrix4x5::new( 4.0, 1.0, 4.0, 0.0, 9.0, 5.0, 6.0, 0.0, 8.0, 10.0, 9.0, 10.0, 11.0, 12.0, 0.0, 0.0, 0.0, 1.0, 0.0, 10.0 ); let cs: CsMatrix<_, _, _> = m.into(); assert!(cs.is_sorted()); let cs_transposed = cs.transpose(); assert!(cs_transposed.is_so...
cs_transpose
identifier_name
cs_matrix.rs
#![cfg_attr(rustfmt, rustfmt_skip)] use na::{Matrix4x5, Matrix5x4, CsMatrix}; #[test] fn cs_transpose() { let m = Matrix4x5::new( 4.0, 1.0, 4.0, 0.0, 9.0, 5.0, 6.0, 0.0, 8.0, 10.0, 9.0, 10.0, 11.0, 12.0, 0.0,
0.0, 0.0, 1.0, 0.0, 10.0 ); let cs: CsMatrix<_, _, _> = m.into(); assert!(cs.is_sorted()); let cs_transposed = cs.transpose(); assert!(cs_transposed.is_sorted()); let cs_transposed_mat: Matrix5x4<_> = cs_transposed.into(); assert_eq!(cs_transposed_mat, m.transpose()) }
random_line_split
cs_matrix.rs
#![cfg_attr(rustfmt, rustfmt_skip)] use na::{Matrix4x5, Matrix5x4, CsMatrix}; #[test] fn cs_transpose()
{ let m = Matrix4x5::new( 4.0, 1.0, 4.0, 0.0, 9.0, 5.0, 6.0, 0.0, 8.0, 10.0, 9.0, 10.0, 11.0, 12.0, 0.0, 0.0, 0.0, 1.0, 0.0, 10.0 ); let cs: CsMatrix<_, _, _> = m.into(); assert!(cs.is_sorted()); let cs_transposed = cs.transpose(); assert!(cs_transposed.is_sorte...
identifier_body
unit_action_system.rs
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // 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 wi...
} } } }
{ attach_action_component!(*action, entity, &mut mtps); }
conditional_block
unit_action_system.rs
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // 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 wi...
// The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PU...
// furnished to do so, subject to the following conditions: //
random_line_split
unit_action_system.rs
// OpenAOE: An open source reimplementation of Age of Empires (1997) // Copyright (c) 2016 Kevin Fuller // // 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 wi...
(&mut self, arg: specs::RunArg, time_step: Fixed) { fetch_components!(arg, entities, [ mut components(action_queues: ActionQueueComponent), mut components(mtps: MoveToPositionActionComponent), mut resource(action_batcher: ActionBatcher), ]); self.turn_accumul...
update
identifier_name